Search code examples
javascriptangularpromisees6-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. 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.


Solution

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