Promise结合FileReader提前resolve,未等待后续异步操作问题咨询
问题分析与解决方案
你的问题核心是对Promise链的链式衔接逻辑理解有偏差,导致myFunction没有等待postCall完成就提前返回了结果。
为什么现在的代码不符合预期?
你看,myFunction里现在直接返回的是to64——也就是只负责Blob转Base64的那个Promise。虽然你在to64.then()里调用了postCall,但这个操作只是挂在to64的回调里,并没有把postCall的Promise整合到myFunction返回的Promise链中。
Promise的then()方法本身会返回一个新的Promise:
- 如果
then的回调返回一个Promise,这个新Promise会等待该Promise完成; - 如果返回普通值,新Promise就直接resolve这个值。
但你现在没有把to64.then(...)的返回值作为myFunction的返回结果,所以外部调用myFunction()时,只会等待to64完成,完全不会管后续的postCall。
修正后的代码
把myFunction的返回值改成to64.then(...)的结果,这样就能把postCall的异步操作纳入整个Promise链:
myFunction(audioFile){ var to64 = this.convertBlobToBase64(audioFile); // 把then链的结果返回,而不是返回原始的to64 return to64.then(function(base64Val){ var nextPromise = postCall(); // 这里可以直接返回nextPromise,then会自动等待它完成 return nextPromise.then(function(postResult){ // 这里处理postCall完成后的逻辑(stuff) // 如果需要把postResult传递给外部的then,直接返回即可 return postResult; }); }); }
简化写法(可选)
你也可以用箭头函数简化代码,让链式结构更清晰:
myFunction(audioFile) { return this.convertBlobToBase64(audioFile) .then(base64Val => postCall()) .then(postResult => { // 处理postCall完成后的逻辑 return postResult; // 传递结果给外部的then }); }
这样修改后,当外部调用myFunction().then(...)时,会先等待Blob转Base64完成,再等待postCall完成,最后才触发外部的then回调,确保数据准备齐全。
内容的提问来源于stack exchange,提问作者JWiley
相关产品推荐
相关产品推荐

