ultra
ultra

Reputation: 33

SyntaxError: await is only valid in async function. Unable to Correct it

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);

Upvotes: 2

Views: 111

Answers (3)

Samvel
Samvel

Reputation: 26

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)
})()

Upvotes: 0

Yansh
Yansh

Reputation: 110

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.

Upvotes: 0

hgb123
hgb123

Reputation: 14881

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)
})()

Upvotes: 3

Related Questions