简体   繁体   English

Function 在 promise 的结果之前返回?

[英]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 is assigned with an undefined value. showPopup 被分配了一个未定义的值。 On debugging, the getShowPopup method is returning value before the promise is executed.在调试时,getShowPopup 方法在 promise 执行之前返回值。 How can I make this synchronous so that it waits for the response and then return the correct result.我怎样才能使这个同步,以便它等待响应,然后返回正确的结果。

I think better approach is to make it like this:我认为更好的方法是让它像这样:

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

now showPopup const should have value.现在 showPopup const 应该有价值。 Other approach is to make function async其他方法是使 function 异步

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

and then you will only have to use key word 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM