ES6系列之Promise, Generator, Async比较

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES6系列之Promise, Generator, Async比较脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

比较Promise, Generator, Async写法:

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();

// step1 with 300
// doIt: 13202.5498046875ms
// step2 with 500
// step3 with 700
// result is 900

Generator

function* doii() {
    console.time("do");
    const time1 = 300;
    const time2 = yield step1(time1);
    const time3 = yield step2(time2);
    const result = yield step3(time3);
    console.log(`result is ${result}`);
    console.timeEnd("do");
}

doii();

let res = doii();
res.next().value
    .then( a => res.next(a).value )
    .then( b => res.next(b).value )
    .then( c => res.next(c).value )
// step1 with 300
// step2 with 500
// step3 with 700
// result is 900
// do: 1506.312744140625ms

Async

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();

// step1 with 300
// step2 with 500
// step3 with 700
// result is 900
// doIt: 1507.68505859375ms

脚本宝典总结

以上是脚本宝典为你收集整理的ES6系列之Promise, Generator, Async比较全部内容,希望文章能够帮你解决ES6系列之Promise, Generator, Async比较所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。