跳到主要内容

async/await 语法问题

语法

  • 执行 async 函数,返回的是 Promise 对象
  • await 相当于 Promise 的 then
async function fn(){
return 100
}
(async function(){
const a = fn() // 执行 async 函数,返回的是 Promise 对象
console.log('a',a) // a Promise {<resolved>: 100}
const b = await fn() // await 相当于 Promise 的 then
console.log('b',b) // b 100
})()

报错无法执行,需要 try…catch 才可捕获异常

(async function(){
console.log('start')
const a = await 100 // 直接返回 100
console.log('a',a)
const b = await Promise.resolve(100) // await 相当于 Promise then
console.log('b',b)
const c = await Promise.reject(300) // 报错,下面无法执行,需要 try...catch
console.log('c',c)
console.log('end')
})() //执行完毕,打印出哪些内容?
//start
//a 100
//b 100
//Uncaught (in promise) 300