1. 原因:
- 在函数内使用 await 时,该函数本身必须携带 async,否则就不能使用 async/await
const foo = async () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Hello,world')
resolve()
}, 1000)
})
}
const bar = () => {
await foo()
}
bar()
const bar = async () => {
await foo();
}
bar()
setTimeout(() => {
await foo();
},1000)
setTimeout(async () => {
await foo();
},100)
const bar = () => {
return (() => {
await foo();
})
}
bar()()
const bar = () => {
return (async () => {
await foo();
})
}
bar()()
- 特殊情况:非函数环境下调用 await 是可以的,比如在 window
const foo = async () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Hello,world')
resolve()
}, 1000)
})
}
await foo()
参考文献 https://bobbyhadz.com/blog/javascript-unexpected-reserved-word-await#:~:text=The%20%22unexpected%20reserved%20word%20await,directly%20enclosing%20function%20as%20async%20.
|