函数在承诺的结果之前返回?

时间:2021-05-27 07:24:47

标签: javascript angular promise es6-promise

getShowPopup(fileName,zoneId) {
        return this.getDataFromServer(fileName,zoneId).then((response) => { 
            return response;
        });
}

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

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

1 个答案:

答案 0 :(得分:0)

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

// 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);
}

然后你只需要使用关键字 await

// 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);