天天看點

TypeScript的async, await, promise,多參數的調用比較(第2篇)

參考部落格: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      

作者:小烏龜

出處:http://www.cnblogs.com/music-liang/

【轉載請注明出處,歡迎轉載】 希望這篇文章能幫到你