ts语言中的asycn与wait

本文通过对比不使用异步、循环嵌套、Promise和async/await四种方式实现定时输出,展示了JavaScript中异步编程的不同方法。重点讨论了事件循环在async函数中的影响,以及如何通过async/await来编写更直观的异步代码。
摘要由CSDN通过智能技术生成

1. 不采用异步方式

如果不采用异步方式,那么同时采用定时功能,数据会同时输出:

setTimeout(function (){
  console.log('Frist')}, 2000)
setTimeout(function (){
  console.log('Second')}, 2000)
setTimeout(function (){
  console.log('Third')}, 2000)

结果:
两秒之后,同时输出:

Frist
Second
Third

2. 采用循环嵌套模式

setTimeout(function (){
  console.log('Frist')
  setTimeout(function (){
    console.log('Second')
    setTimeout(function (){
      console.log('Thirt')
    },2000)
  }, 2000)
}, 2000)

结果:依次间隔两秒输出

Frist
Second
Third

3. 采用Promise模式

const resolver = (msg, timeout) => new Promise((resolve) => {
    console.log(msg);
    setTimeout(resolve, timeout);
});

resolver('First', 500)
    .then(() => resolver('Second', 2000))
    .then(() => resolver('Third', 2000))
    .then(() => resolver('Fourth', 2000));

结果:依次间隔两秒输出(用写同步的语言书写异步的操作)

Frist
Second
Third

4. 采用async/await模式

const resolver = (msg, timeout) => new Promise((resolve) => {
    console.log(msg);
    setTimeout(resolve, timeout);
});
async function run() {
    await resolver('First', 2000);
    await resolver('Second', 2000);
    await resolver('Third', 2000);
    await resolver('Fourth', 2000);
}
run();

结果:依次间隔两秒输出(用写同步的语言书写异步的操作)

Frist
Second
Third

易错点:事件循环问题:

async function fn1 (){
  console.log(1)
  await fn2() // fn2进入微任务队列等待执行
  console.log(2) // 阻塞
}
async function fn2 (){
  console.log('fn2')
}
fn1()
console.log(3)

// 输出结果:1,fn2,3,2

async function fn1 (){
  console.log(1)
  await fn2() // fn2进入微任务队列等待执行
  await fn3() // fn3进入微任务队列等待执行
  console.log(2) // 阻塞
    console.log(3) // 阻塞
}
async function fn2 (){
  console.log('fn2')
}
console.log(4)
async function fn3 (){
  console.log('fn3')
}
fn1()
console.log(3)
console.log(4)
// 输出结果:1,4, fn2,3,4 ,fn3,2,3

结果:
4,1, fn2,3,4 ,fn3,2,3

重点参考文章
1. 极速上手TypeScript」TypeScript之Promise
2. 理解异步函数async和await的用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值