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
上一篇:LeetCode刷题笔记 Java 腾讯 链表 合并两个有序链表


下一篇:马尔科夫链