简体   繁体   中英

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. On debugging, the getShowPopup method is returning value before the promise is executed. 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. Other approach is to make function async

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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