语法错误:等待仅在异步功能中有效。无法更正

时间:2020-08-28 08:17:53

标签: javascript

我无法运行以下代码。 它显示了此错误:

SyntaxError:等待仅在异步功能中有效

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

3 个答案:

答案 0 :(得分:3)

您可以使用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)
})()

答案 1 :(得分: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只能在异步函数中使用。

此处的错误是指最终变量。它必须在异步函数内部。尝试使用下面的代码。

答案 2 :(得分: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)
})()