TypeScript的async, await, promise,多参数的调用比较(第2篇)
参考博客: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
分类:
typescript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?