当前位置:网站首页>await is only valid in async function

await is only valid in async function

2022-06-23 01:54:00 web15085547941

This mistake means await It can only be put in async Internal function , The implication :

  1. await Must be put in the function
  2. Function must have async Modifier

error 1: Not in the function

const myFun = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1)
    },1000)
  })
}
//  error :  Not in the function 
res1 = await myFun();
console.log(res1);

// SyntaxError: await is only valid in async function

error 2: Function does not async Modifier

const myFun = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1)
    },1000)
  })
}
//  error :  Function does not async Modifier 
const myFun2 = () => {
  res1 = await myFun();
  console.log(res1);
}

myFun2();

// SyntaxError: await is only valid in async function

Write it correctly

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

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

myFun2();

// 1
原网站

版权声明
本文为[web15085547941]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220507490861.html