Search code examples
javascriptpromisees6-promise

synchronous multiple promises inside if statement


My function ends before finalizing the promises within the if. The idea is to be able to execute the promises (that are necessary) in a synchronous way for when the object is returned, it is complete and all the promises have finished.

let var1 = '';
let var2 = '';
let var3 = '';

if(condition1){
  promise1().then(result =>{
    var1 = result;
  )
}

if(condition2){
  promise2().then(result =>{
    var2 = result;
  )
}

if(condition3){
  promise2().then(result =>{
    var3 = result;
  )
}

let object = {
  var1: var1,
  var2: var2,
  var3: var3
}

resolve(object);

What I did initially was to use Promise.all, but it did not work, and the function returns the object without finishing the promises. This was my implementation.

let var1 = '';
let var2 = '';
let var3 = '';
let array_promises = [];
if(condition1){
  promise1().then(result =>{
    var1 = result;
    array_promises.push(result);
  )
}

if(condition2){
  promise2().then(result =>{
    var2 = result;
    array_promises.push(result);
  )
}

if(condition3){
  promise2().then(result =>{
    var3 = result;
    array_promises.push(result);
  )
}
.
.
.


Promise.all(array_promises).then(()=>{
  let object = {
   var1: var1,
   var2: var2,
   var3: var3
   .
   .
   .
  }
  resolve(object);
});

It did not work either. returns object without completing the execution of the promises. I do not want to use any third-party npm or anything like that. Any guide or suggestion?, I may be doing something wrong


Solution

  • You need to call Promise.all on an array of Promises - if the array doesn't contain actual Promises, then the Promise.all won't wait for anything, and will resolve as soon as it can. Your array_promises isn't an array of Promises, it's just an array of values that might get pushed to. Try calling Promise.all on the promises themselves instead:

    const condition1 = true;
    const condition2 = false;
    const condition3 = true;
    const promise1 = () => new Promise(resolve => setTimeout(resolve, 200, 'p1'));
    const promise2 = () => new Promise(resolve => setTimeout(resolve, 200, 'p2'));
    const promise3 = () => new Promise(resolve => setTimeout(resolve, 200, 'p3'));
    
    Promise.all(([
      condition1 ? promise1() : '',
      condition2 ? promise2() : '',
      condition3 ? promise3() : '',
    ])).then(([var1, var2, var3]) => {
      const returnObj = {
        var1,
        var2,
        var3,
      };
      console.log(returnObj);
    })

    This works because, in the array passed to Promise.all, any values that are not promises will simply be passed as-is to the .then.

    By your resolve(object);, it looks as if this whole code is inside a Promise constructor. If that's the case, it would probably be better if you instead returned the Promise.all call, instead of explicitly creating another new Promise.