-2

my scenario is:

var data = getData();

function getData(){
    return 8;
}

function closePopup(){
    console.log('close popup executed');
} 

Here I want to call closePopup method on complete execution of getData() function like synchronously.

Thanks Rambabu B

2 Answers2

1

You can use async functions to wait for a Promise.

function closePopup() {
  console.log("Closing popUp");
}

function getData() {
  return new Promise(resolve => {
    setTimeout(function() { //This is to simulate an async call (Like Ajax)
      resolve("Called");
    }, 2000);
  });
}

async function main() { // This is the async function
  console.log('Waiting 2 secs...');
  var data = await getData();
  console.log(data);
  closePopup();
  
  return "Some value if you want!"
}

main().then(v => console.log(v)); //An async function returns a Promise.

Resources

Ele
  • 33,468
  • 7
  • 37
  • 75
  • Since the question is tagged with AngularJS, `Promise` can be replaced with `$q`, and `setTimeout` with `$timeout` – Aleksey Solovey Feb 15 '18 at 15:11
  • I just want to remember you of the comment you wrote a week ago about a question that was "definetly off-topic", and it should be closed without answering as the OP did not show any research effort... – Jonas Wilms Feb 15 '18 at 15:11
  • @AlekseySolovey yes, but this is a guide to show how async function works. – Ele Feb 15 '18 at 15:14
  • @JonasW. **Are you talking about this:** *Too many times, the community answers this kind of question. I don't understand why!... A lot of similar questions are closed because the OP doesn't show any effort. It's very funny, how the community answer this, sometimes close it. It depends whether people wake up with the intention to "help". All these kind of answers deserve to be closed!!*... They are too differents. This one it's about a doubt. That question where I commented, was about a homework question!! **Like I said:** *it depends on how the community wants to help in a specific time*. – Ele Feb 15 '18 at 15:27
0

You can use promises to call the function after completion of getData() function or Inside the getData() function, which would return a promise and you can resolve it here.

var data = getData();
Promise.resolve(data).then(function(value) {
  studentdata = value;
  closePopup();
});
eshunsharma
  • 171
  • 9