【问题标题】:Function returning before the result from a promise?函数在承诺结果之前返回?
【发布时间】:2021-08-15 10:32:36
【问题描述】:
getShowPopup(fileName,zoneId) {
        return this.getDataFromServer(fileName,zoneId).then((response) => { 
            return response;
        });
}

const showPopup = this.Service.getShowPopup(fileName,this.id);

showPopup 被分配了一个 undefined 值。在调试时,getShowPopup 方法在执行 promise 之前返回值。我怎样才能使这个同步,以便它等待响应,然后返回正确的结果。

【问题讨论】:

  • 看起来getShowPopup 返回了一个承诺。你确定showPopupundefined 吗?顺便说一句,.then(response => {return respone;} 没有意义,您可以删除该部分。
  • “异步以便等待响应”——这与异步的含义相反。

标签: javascript angular promise es6-promise


【解决方案1】:

我认为更好的方法是这样:

// it should return Promise
function getShowPopup(fileName,zoneId) {
        return this.getDataFromServer(fileName,zoneId);
}

// and then when you want to get value from this api call
const showPopup = this.Service.getShowPopup(fileName,this.id)
    .then(response => response)
    .catch(error => console.log(error));

现在 showPopup const 应该具有价值。 另一种方法是使函数异步

async function getShowPopup(fileName,zoneId) {
        return this.getDataFromServer(fileName,zoneId);
}

然后你只需要使用关键字等待

// but if api call returns error, it will not be caught so you should put this call in try catch block
const showPopup = await this.Service.getShowPopup(fileName, this.id);

【讨论】:

  • 我只是附加了等待,而不是在进一步执行之前等待响应。
    const showPopup = await this.Service.getShowPopup(fileName, this.id);
  • getDataFromServer(param1, param2) { return new Promise((resolve, reject) => { let subs: Subscription = this.read.subscribe((res) => { subs.unsubscribe(); resolve(true); }, (err) => { subs.unsubscribe(); resolve(false); }) }) }
  • 您不必创建函数async 就可以使用awaitawait 适用于 promisesgetShowPopup 已经在第一个示例中返回了一个承诺(因为 this.getDataFromServer 确实如此)。
  • @jitenderd 你能贴出getDataFromServer函数所在的整段代码(我认为是一个类)吗?也许编辑你的问题,它会更容易阅读
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2020-03-06
  • 1970-01-01
相关资源
最近更新 更多