AngularJS Typescript – Wait for asynchronous promise to resolve

For example, we want to have a function to resolve a value of 10.

function1() {
  return new Promise(resolve => {
    // some long processing
    resolve(10);
  }
}

To call the function,

function1().then(response => console.log(response));
console.log(2);

There are two scenarios. Either the output would be:

10
2

or

2
10

It is because it depends on how long it takes for function1() to resolve or finish its execution.

If we want to wait until function1() to finish execution before we print out ‘2’ to console, then we have to do:

var promise1 = function1();
Promise.resolve(promise1).then(response => {
  console.log(response);
});
console.log(2);

The output would be:

10
2

If we have two functions that return a Promise, then to wait until both functions finish execution before executing another statement is as following:

var promise1 = function1(); // returns 2
var promise2 = function2(); // returns 10
Promise.all([promise1, promise2]).resolve([value1, value2] => {
  console.log(value1);
  console.log(value2);
});

The output is:

2
10