在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
参考博客: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
|
请发表评论