0

I want to create some code that executes sequentially as follows:

console.log('Called before the function containing a promise');
var result = getSomeData();
console.log('Called after getSomeData() has completed fully');

getSomeData() {
  var stuff = <do something here>;
  return dbGetDocument(stuff).then((result)=>{
      return result;
    });
}

dbGetDocument() is an existing library function (written by someone else) that returns a promise.

When running this code the final console.log gets executed before the dbGetDocument.then has returned it's result.

Bill Noble
  • 6,466
  • 19
  • 74
  • 133
  • Just put the console.log inside the dbGetDocument.then function. Right before returning result – Tah Mar 28 '17 at 12:38
  • Sorry, the point of the question was to have something execute after the getSomeData () had completed, not after the dbGetDocument. Console.log was just an example. – Bill Noble Mar 28 '17 at 12:40
  • Thanks for the link @estus I still can't work out how to do exactly what I want. – Bill Noble Mar 28 '17 at 13:19
  • In Javascript, you can't make a function "wait" to return until an async operation is done. You just can't. You will have to restructure your code to pass a callback into the function or have your function return the promise. Your options are further explained in the question yours is marked a dup of. – jfriend00 Mar 28 '17 at 13:21
  • There are answers in dupe question that closely resemble your case with promises. `getSomeData()` should be chained with `.then(...)`. – Estus Flask Mar 28 '17 at 13:31

0 Answers0