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

Function returning before the result from a promise?

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

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

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

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

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