JavaScript:如何从含.then()的异步函数中返回计算结果?
解决异步函数返回值问题:让parentFunction获取childFunction的计算结果
你的问题核心是没有正确返回Promise链,导致外层函数拿不到异步操作后的计算结果。按照下面的方式修改代码,就能解决问题:
修改后的完整代码
async function parentFunction(){ // 用await接收异步返回值,或通过.then链式调用处理 let result = await childFunction() // 此处可直接使用计算后的result console.log(result) } function childFunction(){ // 假设listofQueries是多个Firebase异步调用的Promise数组 // 关键1:在Promise.all前添加return,让childFunction返回整个Promise链 return Promise.all(listofQueries) .then((res) => { // 基于所有异步调用的结果res做计算,而非原listofQueries let result = _doMathStuff(res) // 关键2:return将计算结果传递到Promise链的下一个环节 return result }) }
关键修改点说明
- childFunction返回Promise链:只有返回
Promise.all(...)这条链,parentFunction才能通过异步语法(await或.then)接收后续的计算结果。如果不添加return,childFunction默认返回undefined,自然拿不到目标值。 - .then内部返回计算结果:这里的return会把处理后的结果作为新Promise的resolve值,传递给外层调用者。
- parentFunction用异步方式接收:如果不想用async/await,也可以用.then链式调用:
function parentFunction(){ childFunction().then(result => { console.log(result) // 在此处处理result }) }
额外提示:原代码里用new Promise包裹asyncFirebaseCall是多余的——Firebase的异步API本身就返回Promise,直接把它加入listofQueries数组即可,无需额外包装。
内容的提问来源于stack exchange,提问作者dahallor
相关产品推荐
相关产品推荐

