关于javascript:asyncawait和Promise区别

27次阅读

共计 2189 个字符,预计需要花费 6 分钟才能阅读完成。

async/await 的劣势:能够很好地解决 then 链

对于繁多的 Promise 链其实并不能发现 async/await 的劣势,当须要解决由多个 Promise 组成的 then 链的时候,劣势就能体现进去了,
接下来间接上代码:

/**
 * 传入参数 n,示意这个函数执行的工夫(毫秒)* 执行的后果是 n + 200,这个值将用于下一步骤
 */
function takeLongTime(n) {
    return new Promise(resolve => {setTimeout(() => resolve(n + 200), n);
    });
}

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

function step2(n) {console.log(`step2 with ${n}`);
    return takeLongTime(n);
}

function step3(n) {console.log(`step3 with ${n}`);
    return takeLongTime(n);
}

当初用 Promise 形式:

function doIt() {console.time("doIt");
    const time1 = 300;
    step1(time1)
        .then(time2 => step2(time2))
        .then(time3 => step3(time3))
        .then(result => {console.log(`result is ${result}`);
            console.timeEnd("doIt");
        });
}

doIt();

// c:vartest>node --harmony_async_await .
// step1 with 300
// step2 with 500
// step3 with 700
// result is 900
// doIt: 1507.251ms

输入后果 resultstep3() 的参数 700 + 200 = 900doIt() 程序执行了三个步骤,一共用了 300 + 500 + 700 = 1500 毫秒,和 console.time()/console.timeEnd() 计算的后果统一。
用 async/await 的形式:

async function doIt() {console.time("doIt");
    const time1 = 300;
    const time2 = await step1(time1);
    const time3 = await step2(time2);
    const result = await step3(time3);
    console.log(`result is ${result}`);
    console.timeEnd("doIt");
}

doIt();

后果和之前的 Promise 是统一的,然而这个代码缩小了很多

当初改一下要求:

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

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

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

Promise 实现:

function doIt() {console.time("doIt");
    const time1 = 300;
    step1(time1)
        .then(time2 => {return step2(time1, time2)
                .then(time3 => [time1, time2, time3]);
        })
        .then(times => {const [time1, time2, time3] = times;
            return step3(time1, time2, time3);
        })
        .then(result => {console.log(`result is ${result}`);
            console.timeEnd("doIt");
        });
}

doIt();

async/await 实现:

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

doIt();

// c:vartest>node --harmony_async_await .
// step1 with 300
// step2 with 800 = 300 + 500
// step3 with 1800 = 300 + 500 + 1000
// result is 2000
// doIt: 2907.387ms

PS:因为在 Promise 中。咱们有时会被回绝拜访,这样 Async/Await 让 try/catch 能够同时解决同步和异步谬误。

具体对于 async/await 含意和用法能够参考:

http://www.ruanyifeng.com/blo…

正文完
 0