Solve error & JS & async/await & Uncaught (in promise) SyntaxError: Unexpected reserved word (at

1. Reason:

  1. 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 没有加上 async
}
bar()

const bar = async () => {
    
    
	await foo(); // 正确
}
bar()

setTimeout(() => {
    
    
	await foo(); // 错误,匿名函数也是一个函数,没有带上 async
},1000)

setTimeout(async () => {
    
    
	await foo(); // 正确
},100)



const bar = () => {
    
    
	return (() => {
    
    
		await foo(); // 错误
	})
}
bar()()
const bar = () => {
    
    
	return (async () => {
    
    
		await foo(); // 正确
	})
}
bar()()

  1. 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() // 全局环境下可以直接使用 await

Reference
https://bobbyhadz.com/blog/javascript-unexpected-reserved-word-await#:~:text=The%20%22unexpected%20reserved%20word%20await , directly%20enclosing%20function%20as%20async%20 .

Guess you like

Origin blog.csdn.net/cookcyq__/article/details/123976301