Home > Software engineering >  Promise.all is resolving conditional promises
Promise.all is resolving conditional promises

Time:01-22

i have written a function that will either return the input promise of an empty promise based on a condition

export const promiseUtility = (promise, condition) => {
  if (condition) {
    return promise;
  } else {
    return new Promise(resolve => resolve());
  }
};

when i am calling this function such that

    const arr= [
      promiseUtility({
        promise: getUsers(req, type, id),
        condition: req.body.shouldGetUsers
      }),
      promiseUtility({
        promise: getObjects(req, type, id),
        condition: req.body.shouldGetObjects,
    ];

    const [users =[], objects =[]] = await Promise.all(arr)

The problem that i am facing is when a condition like shouldGetUsers is false, even then the original promise i.e. getUsers(req) is getting resolved. It looks like this is because i have called that getUsers function. How can i deal with such situation

CodePudding user response:

If you don't want a promise to resolve, you must not create it in the first place. But you already create a promise when you pass getUsers(req, type, id) as the promise argument to your promiseUtility function.

I suggest you use a conditional operator instead, which will only execute the getUsers function if the condition is true:

const arr = [
  req.body.shouldGetUsers ? getUsers(req, type, id) : Promise.resolve(),
  req.body.shouldGetObjects ? getObjects(req, type, id) : Promise.resolve()
];

CodePudding user response:

Agreed with Heiko's answer. But, i figured out if we want to make a generic utility function for that then we can do it like this.


export const promiseUtility = (promise, condition) => {
  if (condition) {
    return promise();
  } else {
    return new Promise(resolve => resolve());
  }
};

const arr= [
  promiseUtility({
    promise: () => getUsers(req, type, id),
    condition: req.body.shouldGetUsers
  }),
  promiseUtility({
    promise: () => getObjects(req, type, id),
    condition: req.body.shouldGetObjects,
  })
];

const [users =[], objects =[]] = await Promise.all(arr)
  • Related