首页 > 其他 > 详细

TypeScript的async, await, promise,多参数的调用比较(第2篇)

时间:2020-04-21 11:19:26      阅读:155      评论:0      收藏:0      [点我收藏+]

 

参考博客:https://blog.csdn.net/u012863664/article/details/77881921

 

TypeScript的async, await, promise,多参数的调用比较

现在把业务要求改一下,仍然是三个步骤,但每一个步骤都需要之前每个步骤的结果。

 

async function takeLongTime(n:number){
    return new Promise(resolve=>{
        setTimeout(() => {
            resolve(n+300);
        }, n);
    });
}

function step1(n:number){
    console.log(`step1 with ${n}`);
    return takeLongTime(n);
}

function step2(m:number , n:number){
    console.log(`step2 with ${m} and ${n}`);
    return takeLongTime(m + n);
}

function step3(k:number, m:number, n:number){
    console.log(`step3 with ${k}, ${m} and ${n}`);
    return takeLongTime(k + m + n);
}

////async / wait
async function doIt1()
{
    console.time("doIt1");
    const time1 = 300;
    const time2 = await step1(time1);
    const time3 = await step2(time1, <number>time2);
    const result = await step3(time1, <number>time2,  <number>time3);
    console.log(`result is ${result }`);
    console.timeEnd("doIt1");
}

//doIt1();
// step1 with 300
// step2 with 300 and 600
// step3 with 300, 600 and 1200
// result is 2400



////promise 方式实现
function doIt2()
{
    console.time("doIt2");
    const time1 = 300;
    step1(time1)
    .then(time2=>{
        return step2(time1, <number>time2)
        .then(time3=>[time1, time2, time3]);
    })
    .then(times=>{
        const [time1, time2, time3] = times;
        return step3(<number>time1, <number>time2, <number>time3);
    })
    .then(result =>{
        console.log(`result is ${result}`);
        console.timeEnd("doIt2");
    })
}

doIt2();
// step1 with 300
// step2 with 300 and 600
// step3 with 300, 600 and 1200
// result is 2400
// doIt2: 3310.490966796875ms
// doIt2: 3310.550ms

 

TypeScript的async, await, promise,多参数的调用比较(第2篇)

原文:https://www.cnblogs.com/music-liang/p/12743144.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!