TypeScript中async/await未等待函数完全执行问题求助
问题描述
我需要先从storage获取username、password和title,再调用API获取数据,因此在调用API前多次使用async/await。数据能正确获取,但refresh的timeout函数却在getData完全执行前就完成了。尝试过移除async/await,调整代码后仍未解决,console.log与event.target.complete总是先于getData执行完成。
代码示例1
doRefresh(event) { setTimeout(async () => { await this.storage.get('username').then(async username => { await this.storage.get('password').then(async password => { await this.storage.get('title').then(async tempName => { await this.myService.getJSON(username, password, tempName, "keywordA", this.section).then(async ()=> { await this.myService.getJSON(username, password, tempName, "keywordB", "trainingInfo"); }).finally(async ()=> { await this.getData(); console.log('done'); event.target.complete(); }); }) }) }); }, 2500); }
代码示例2
doRefresh(event) { setTimeout(() => { this.storage.get('username').then(username => { this.storage.get('password').then(password => { this.storage.get('title').then(tempName => { this.myService.getJSON(username, password, tempName, "keywordA", this.section).then(()=> { this.myService.getJSON(username, password, tempName, "keywordB", "trainingInfo"); }).finally(()=> { this.getData(); console.log('done'); }); }) }) }); event.target.complete(); }, 2500); }
问题原因
- async/await与.then()混用:嵌套的.then()和await叠加导致异步流程控制混乱,部分异步操作没有被正确等待
- 示例2的complete执行时机错误:
event.target.complete()直接写在setTimeout回调的最外层,完全没等内部的storage读取、API调用和getData执行就触发了 - 示例1的finally逻辑有漏洞:虽然把complete放在finally里,但内层的.then()没有返回Promise,await无法正确捕获其完成状态
解决方案
彻底改用async/await简化异步流程,抛弃嵌套的.then(),确保所有异步操作按顺序执行并被正确等待:
doRefresh(event) { setTimeout(async () => { try { // 依次读取storage参数,避免嵌套 const username = await this.storage.get('username'); const password = await this.storage.get('password'); const tempName = await this.storage.get('title'); // 按顺序调用两个API,确保前一个执行完成再启动下一个 await this.myService.getJSON(username, password, tempName, "keywordA", this.section); await this.myService.getJSON(username, password, tempName, "keywordB", "trainingInfo"); // 等待getData完全执行完毕 await this.getData(); console.log('done'); event.target.complete(); } catch (error) { // 捕获所有异常,避免刷新流程卡死 console.error('刷新失败:', error); event.target.complete(); // 即使出错也要结束refresh状态 } }, 2500); }
方案说明
- 用async/await替代嵌套.then(),让异步代码逻辑更清晰,所有步骤按顺序执行,确保每一步都等待上一步完成
- 加入try/catch块处理异常,避免某个异步操作失败后,refresh状态一直无法结束
- 所有异步操作都用await包裹,保证getData执行完成后,才会触发console.log和event.target.complete()
内容的提问来源于stack exchange,提问作者qwerty
相关产品推荐
相关产品推荐

