0
votes

I'm using Promise.all function to resolve the multiple promises concurrently. See the below code -

function check1() {
  console.log('check 1 invoked') 
  return new Promise((resolve, reject) => {
    setTimeout(()=> resolve('check1'), 4000);
  }) 
}

function check2() {
  console.log('check2 invoked')
  return new Promise((resolve, reject) => {
    setTimeout(()=> resolve('check2'), 4000);
  }) 
}

var arr = [check1(), check2()];

Promise.all(arr)
 .then((response) => console.log('response======>',response))
 .catch((error) => console.error('error',error))

The problem with the above approach is that when I create the promise array, The respective functions gets invoked. I want to change the above code in the manner that two functions call only from the promise.all function.

Note - Need to store the promises functions in the array. Like I'm doing as var arr.

2
arr = [ check1, check2 ]; Promise.all( arr.map( a => a() ).then ... ? - Sirko
check1() calls the check1 function right then and there. That's not what you want. You want a reference to the function so the promise can call it later. You can get that by simply omitting the (). - Michael Geary

2 Answers

1
votes

This should do it, do not make an array of promises but an array of functions, then map the functions to promises:

function check1() {
  console.log('check 1 invoked') 
  return new Promise((resolve, reject) => {
    setTimeout(()=> resolve('check1'), 4000);
  }) 
}

function check2() {
  console.log('check2 invoked')
  return new Promise((resolve, reject) => {
    setTimeout(()=> resolve('check2'), 4000);
  }) 
}
//do not store the promises, store the funciton that creates a promise
var arr = [check1, check2];

Promise.all(
  //map functions to promises
  arr.map(fn=>fn())
)
.then((response) => console.log('response======>',response))
.catch((error) => console.error('error',error))
-1
votes

You can do in this way too -

 var check1 = new Promise((resolve, reject) => { 
      setTimeout(()=> resolve('check1'), 4000);
    }); 
    var check2 = new Promise((resolve, reject) => { 
       setTimeout(()=> resolve('check2'), 4000);
    });
    Promise.all([check1, check2]).then(values => { 
      console.log(values);
    }, reason => {
      console.log(reason)
    });