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
相关推荐
89500297 2020-06-07
陈旭阳 2020-06-02
前端开发Kingcean 2020-05-29
Magicsoftware 2020-03-28
LorenLiu 2020-03-28
Bonrui编程路 2020-06-07
niehanmin 2020-05-19
Magicsoftware 2020-03-28
lyg0 2020-02-18
88520191 2020-01-30
前端开发Kingcean 2020-01-23
csuzxm000 2020-01-10
whynotgonow 2020-01-05
89500297 2020-01-03
88520191 2019-12-30
Trustport 2019-12-16
wujiajax 2014-01-13