Search code examples
javascriptfunctionecmascript-6promisees6-promise

Two asynchronous functions and third function to be executed after first two is executed


Say, I have three javascript functions

  1. function1 and function2 are executed asynchronously
  2. function2 is to be executed after first two is executed completely

How can this be worked out?


Solution

  • Thanks all. I tried all your solutions. Didn't quite work. I created a solution myself after trying for a while. Here it is:

    let promise1 = new Promise(function(resolve, reject) {
      setTimeout(() => resolve("promise1"), 1000);
    });
    
    let promise2 = new Promise(function(resolve, reject) {
      setTimeout(() => resolve("promise2"), 4000);
    });
    
    Promise.all([promise1, promise2])
    .then(result => {
      console.log(result);
    });
    

    It creates two functions that runs the two functions as resolve. Then it is passed to Promise.all in an array, and the third function can be run in the then block of Promise.all.