async和awiat

async和awiat(异步函数策略)

//async标识函数是异步函数,所有async标志的函数都有then属性,then(onResolve, onReject),onResolve接收函数return的结果,onReject接收throw的结果

async function a() {
   return 'fine'
}
a().then(console.log)   //'fine'

async function b() {
   throw 'err
}
b().catch(console.log)     //'err'

//await只有标识(期约)或(async标志的函数)才有意义;会等到(该期约解决/拒绝)或(async函数return/throw)后再执行下文,如果async函数没有return/throw则await无效
async function foo() {
   await new Promise(() => {
      setTimeout(() => {
         resolve(1)
      }, 1000)
   })
   console.log(2)
}
foo() //1s后再打印2

//没有await,或await不是用于标识期约,那就和普通函数没区别

async function foo() {
   await Promise.resolve(1)
   console.log('foo')
}
funtion baz() {
   console.log('baz')
}
foo()
baz()
//先打印'baz'后打印'foo'。因为有期约,foo暂停了一下

sleep()

通过自己用async/await实现一个暂停函数
async function sleep(delay) {
   return new Promise((resolve) => setTimeout(resolve, delay))    //此处若没有return则不能起到sleep作用
}
async function foo() {
   console.log(6)
   await sleep(1000)
   console.log(8)
}
foo()  //6(1s后)8

posted on 2022-01-28 20:30  In-6026  阅读(175)  评论(0)    收藏  举报

导航