0
点赞
收藏
分享

微信扫一扫

await is only valid in async function

以沫的窝 2022-02-22 阅读 65

这个错误的意思是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
举报

相关推荐

0 条评论