async & await

2021-09-17  本文已影响0人  hszz

https://es6.ruanyifeng.com/?search=promise&x=0&y=0#docs/async

// 例1
async function asyncPrint(value, ms) {
    await new Promise( res => {
        console.log('wait')
        setTimeout(res, ms)
    })
    console.log(value)
}
asyncPrint('hello world', 1000)
// 例2
async function f() {
    // 等同于
    // return 123;
    return await 123;
  }
  
  f().then(v => console.log(v))
// 例3
// 有多个await语句,可通过try catch捕获错误
async function f() {
    try {
        await Promise.reject('error')
    }catch(e) {

    }
    return await Promise.resolve('hello world')
}

f().then( v => console.log(v))
上一篇 下一篇

猜你喜欢

热点阅读