skip to Main Content

So I have a bunch of promises I’m trying to batch complete like so:

let promises = [];
let fixedValues = [];
let shouldIQuit = false;
let value = {
    b: 1
};

promises.push(
   new Promise(async (resolve, reject) => {
      const shouldquit = await shouldIQuit(shouldIQuitValue);

      if(shouldquit === true) {
          const fixedValue = await Values.fixThisValue(value);

          if(!fixedValue.a) {
            resolve();
           }

         fixedValues.push(fixedValue);
      }

    resolve();
});

await Promise.all(promises);

the other functions can do anything, but I need both to be awaited. It should first call the shouldIquit function, check that value, then await the result of fixThisValue and then determine if that number should be put into the array or not, and I need to do this all in parallel.

However, I’m noticing that sometimes when fixedValue comes back without fixedValue.a and it successfully hits that resolve(); in the if, it still makes it down to push the fixed value into the array fixedValues when it shouldn’t. I’m thinking it’s the async in the promise creating a problem. Any help with that is much appreciated.

2

Answers


  1. when fixedValue comes back without fixedValue.a and it successfully hits that resolve(); in the if, it still makes it down to push the fixed value into the array fixedValues when it shouldn’t

    I think you’re hoping that resolve() works as a return statement (exiting the function).

             const fixedValue = await Values.fixThisValue(value);
    
              if(!fixedValue.a) {
                resolve();
               }
    
             fixedValues.push(fixedValue);
    

    resolve() doesn’t exit the function. You could update your code to do an early return

    if(!fixedValue.a) {
      resolve();
      return;
    }
                
    fixedValues.push(fixedValue);
    

    or you could add an else block

    
    if(!fixedValue.a) {
      resolve();
    } else {
      fixedValues.push(fixedValue);
    }
    
    Login or Signup to reply.
  2. You need to return resolve() otherwise the code will keep running past the ‘if’.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search