0
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.

jitenderd
  • 181
  • 3
  • 15
  • 6
    It looks like `getShowPopup` returns a promise. Are you sure `showPopup` is `undefined`? Btw, there is no point in doing `.then(response => {return respone;}`, you can just remove that part. – Felix Kling May 27 '21 at 07:26
  • 2
    Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Reyno May 27 '21 at 07:27
  • 4
    "asynchronous so that it waits for the response" — That's the opposite of what asynchronous means. – Quentin May 27 '21 at 07:27

1 Answers1

0

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

frozzen10
  • 101
  • 4
  • I just appended await and not its waiting for the response before executing further.
    `const showPopup = await this.Service.getShowPopup(fileName, this.id);`
    – jitenderd May 27 '21 at 08:02
  • `getDataFromServer(param1, param2) { return new Promise((resolve, reject) => { let subs: Subscription = this.read.subscribe((res) => { subs.unsubscribe(); resolve(true); }, (err) => { subs.unsubscribe(); resolve(false); }) }) }` – jitenderd May 27 '21 at 08:53
  • You don't have to make the the function `async` to be able to use `await`. `await` works with *promises*. `getShowPopup` already returns a promise in the first example (because `this.getDataFromServer` does). – Felix Kling May 27 '21 at 12:10
  • @jitenderd can you post whole piece of code (I think it is a class) where getDataFromServer function is located? maybe edit your question, it will be easier to read – frozzen10 May 28 '21 at 07:19