其他分享
首页 > 其他分享> > await is only valid in async function

await is only valid in async function

作者:互联网

这个错误的意思是await只能放到async函数内部,言下之意:

  1. await必须放到函数里
  2. 函数必须有async修饰符

错误1: 没有放到函数里

const myFun = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1)
    },1000)
  })
}
// 错误: 没有放在函数里
res1 = await myFun();
console.log(res1);

// SyntaxError: await is only valid in async function

错误2: 函数没有async修饰符

const myFun = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1)
    },1000)
  })
}
// 错误: 函数没有async修饰符
const myFun2 = () => {
  res1 = await myFun();
  console.log(res1);
}

myFun2();

// SyntaxError: await is only valid in async function

正确写法

const myFun = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1)
    },1000)
  })
}

const myFun2 = async () => {
  res1 = await myFun();
  console.log(res1);
}

myFun2();

// 1

标签:function,res1,resolve,const,myFun,await,only,async
来源: https://blog.csdn.net/web15085181368/article/details/123079437