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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM