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

相关推荐