ts语言中的asycn与wait

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的用法

猜你喜欢

转载自blog.csdn.net/qq_42974034/article/details/131967174