如何在Angular业务场景中正确使用await控制异步方法执行顺序
解决方案
前置要求
- 异步方法
drawOneTrip、changeTime必须返回Promise实例,如果原有方法是回调式写法,需要先封装为Promise返回 - 原生
Array.forEach不支持异步等待,需要更换遍历方式
改后完整代码
// 方法前加async关键字,支持内部使用await async updateMap() { this.paramsTemp = 0; if(this.updateMapCheck == true){ this.loading = true; // 方式1:所有drawOneTrip并行执行,效率更高(无顺序要求选这个) const drawPromiseList = [] this.arrOfDisplays.forEach((display, index) => { if (display.removed == true && this.locationsToSend[index + 1]) { // 收集所有异步任务的Promise drawPromiseList.push(this.drawOneTrip(index, index + 1, index)) display.removed = false; } }) // 等待所有drawOneTrip执行完成 await Promise.all(drawPromiseList) /* 方式2:drawOneTrip按遍历顺序逐个执行(有顺序要求选这个) for (let index = 0; index < this.arrOfDisplays.length; index++) { const display = this.arrOfDisplays[index] if (display.removed == true && this.locationsToSend[index + 1]) { await this.drawOneTrip(index, index + 1, index) display.removed = false; } } */ // 同步遍历逻辑,直接执行即可 this.markersArr.forEach((marker, index) => { marker.set("label", { text: "" + index, color: "white" }); }); // 等待changeTime执行完成 await this.changeTime(); // 全部完成后执行收尾 this.loading = false; this.map.setZoom(14); } else { this.showToasterErrorUpdateMap(); } }
逻辑说明
- 并行执行
drawOneTrip适合无先后依赖的场景,执行速度更快;串行执行适合前一个drawOneTrip完成后才能执行下一个的场景 - 可以根据业务需要在外层加
try/catch捕获异步过程中抛出的错误,避免进程崩溃
内容的提问来源于stack exchange,提问作者Kayo
相关产品推荐
相关产品推荐

