1. Reason:
- When using await in a function, the function itself must carry async, otherwise async/await cannot be used
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()()
- Special case: It is possible to call await in a non-function environment, such as in window
const foo = async () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Hello,world')
resolve()
}, 1000)
})
}
await foo()
Reference
https://bobbyhadz.com/blog/javascript-unexpected-reserved-word-await#:~:text=The%20%22unexpected%20reserved%20word%20await , directly%20enclosing%20function%20as%20async%20 .