1

Condition

first two async functions start at the same time
don't know which one finish first

Need to execute a third function on the completion of both of these.

Trying to use promise. Please help achieving it using promise and some other way also if its possible.

something i tried not sure if it's right...

function foop(a){
 return new Promise(function(resolve, reject){
   window.setTimeout(function(){
   console.log("first promise executed");
   }, 2000);  
   window.setTimeout(function(){
   console.log("second promise executed");
   if(a>5) resolve(a+10);

   }, 2000);

  if(a<5) reject("error");
 });
}

foop(12).then(function(val){
  window.setTimeout(function(){
   console.log("first then executed -"+ val);
  }, 1000);
}).then(function(val){
  window.setTimeout(function(){
  console.log("second then executed -"+ val);
  }, 500);
}).catch(function(err){
   console.log("error occured");
});

Expected output order

first promise executed      //or second promise executed
second promise executed     // or first promise executed
first then executed -22         //only executed after first two async completes in any order
second then executed -22        // execute after the third async completes (first then completes)
error occured                // in case of reject

1 Answer 1

2

Use Promise.all:

console.log('starting...');

// example function: sleep for 'delay' ms then resolve to 'value'
const wait = (delay, value) => new Promise((resolve, reject) => setTimeout(() => { console.log('done:', value); resolve(value); }, delay));

// start two async functions at the same time
// (in this case, they complete in random order)
const firstPromise = wait(900 + 200 * Math.random(), 'first');
const secondPromise = wait(900 + 200 * Math.random(), 'second');

// Promise.all will wait until all promises given are resolved:
Promise.all([ firstPromise, secondPromise ])
  .then((results) => {
    // if all promises are resolved, results is an array of the
    // result values from each, in the order they are given
  
    console.log(results); // = [ 'first', 'second' ]

    // run some other function again...
    return wait(500, 'third');
  })
  .then((result) => {
    // 'result' is the result from the third function
    
    // more functions, etc...
    return wait(800, 'fourth'); 
  })
  .then((result) => {
   
    // you can even use Promise.all again to run two functions simultatenously, inside a .then
    return Promise.all([
       wait(1100, 'fifth'),
       wait(900, 'sixth')
    ]);
  })
  // etc...
  .catch((error) => {
    // if any promise fail, error will be the error from the first to fail
    
    console.error('Error:', error);
  });

Sign up to request clarification or add additional context in comments.

4 Comments

first and second will start together as expected and then the third in then BUT then i need to execute the forth after this third function in then.
If you need to execute a fourth function, then you should chain another .then call to Promise.all. As long as each .then-function in the chain returns a promise, they will always be run sequentially, e.g., each one after the previous promise was resolved.
can you please :) add what you said in the comment to the code ? REQUEST
Can you please tell when to use "defer" , as i couldn't find anything over here - developer.mozilla.org/en/docs/Web/JavaScript/Reference/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.