letpromise = async () => { return10 } let res = awaitpromise() console.log(res) // 10
右边如果是一个失败状态的promise,那么await会直接抛出异常
1 2 3 4 5 6 7
letpromise = async () => { // return 10 thrownewError("something went wrong"); } let res = awaitpromise() console.log(res) // Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
// 这个函数必须使用async修饰,因为await必须在async修饰的函数使用 asyncfunctionfun() { try { let res = awaitpromise() console.log(res) // 这行代码不会执行,因为await报异常,在同一个函数内,后续代码会等待await执行之后在执行 } catch (e) { console.log("catch: " + e) } // Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules }