await is only valid in async function

胡聊前端發表於2020-12-12

這個錯誤的意思是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

相關文章