函数在Promise返回结果前执行结束返回undefined,如何让其等待异步结果?
问题原因
getShowPopup 本身返回的是 Promise 实例,你同步调用时拿到的是处于 Pending 状态的 Promise 对象,不是实际的接口返回值,直接读取自然拿不到结果。JavaScript 原生不支持将异步IO逻辑改成完全同步阻塞的执行方式,你需要用 Promise 配套的语法来获取异步返回结果。
解决方案
方式1:使用 .then 链式回调
在返回的 Promise 后挂载回调函数,接口返回结果后会自动触发回调,你可以在回调内处理后续业务逻辑:
this.Service.getShowPopup(fileName, this.id).then(showPopup => { // 所有需要用到showPopup的逻辑都要写在这个回调内部 console.log(showPopup) })
方式2:使用 async/await 语法糖(更推荐)
将调用逻辑所在的函数用 async 修饰,在调用异步方法前加 await 关键字,就可以像写同步代码一样获取异步返回值:
// 外层函数必须加async修饰 async handleShowPopup () { const showPopup = await this.Service.getShowPopup(fileName, this.id) // 此处可以直接使用showPopup的值 console.log(showPopup) }
代码优化点
你当前写的 getShowPopup 方法里的 .then 是冗余逻辑,直接返回接口调用的返回值即可,效果完全一致:
getShowPopup(fileName,zoneId) { return this.getDataFromServer(fileName,zoneId) }
内容的提问来源于stack exchange,提问作者jitenderd
相关产品推荐
相关产品推荐

