2

I am unable to run the following code. It shows me this error:

SyntaxError: await is only valid in async function

const Prom = async() => {
  return new Promise((resolve, reject) => {
    let a = 2;
    if (a == 2) {
      resolve('Its working');
    } else {
      reject('Its not working');
    }
  });
};
const final = await Prom();
console.log(final);

0

3 Answers 3

3

You could use IIFE

const Prom = async () => {
  return new Promise((resolve, reject) => {
    let a = 2
    if (a == 2) {
      resolve('Its working')
    } else {
      reject('Its not working')
    }
  })
}

;(async function() {
  const final = await Prom()
  console.log(final)
})()

Sign up to request clarification or add additional context in comments.

Comments

0

const Prom = async () => {
  return new Promise((resolve, reject) => {
    let a = 2;
    if (a == 2) {
      resolve('Its working');
    } else {
      reject('Its not working');
    }
  });
};


const final = async () => {
  const result = await Prom();
  console.log(result);
};

final();

await can only be used inside an async function.

The error here is referring to the final variable. It has to be inside of an async function. Try using the below code.

Comments

0
const prom = new Promise((resolve, reject) => {
    let a = 2;
    if (a == 2) {
      resolve('Its working');
    } else {
      reject('Its not working');
    }
});
(async function() {
  const final = await prom;
  console.log(final)
})()

1 Comment

adding a verbal explanation can be helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.