zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    [TCP/IP]TCP的三次握手和四次挥手

    思考
    jQuery完整的事件委托(on())
    jQuery队列动画
    jQuery自定义动画
    jQuery淡入淡出
    jQuery滑动动画
    jQuery基本动画
    jQuery基础3
  • 原文地址:https://www.cnblogs.com/music-liang/p/12743144.html
Copyright © 2011-2022 走看看