-1

How can I apply logic in case a set of Promises are rejected (all of them)?

validUserIdPromise = checkValidUserId(id)
  .then(() => console.log("user id")
  .catch(() => console.log("not user id")

validCarIdPromise = checkValidCarId(id)
  .then(() => console.log("car id")
  .catch(() => console.log("not car id");

// TODO how to call this? console.log("neither user nor car");

To broaden my question: is it recommended to use Promise.reject() for normal flow control of a JavaScript app, or rather use it only when something goes wrong?

Use case: my nodeJs app receives a uuid from a client, and responds based on matching resource (user or car in the example).

Jonas
  • 121,568
  • 97
  • 310
  • 388
nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95
  • Are you trying to determine if both `validUserIdPromise` and `validCarIdPromise` are rejected? What should occur if only one `Promise` is rejected? – guest271314 Jan 28 '18 at 18:08
  • Yes, I'm trying to determine that. – nagy.zsolt.hun Jan 28 '18 at 18:09
  • Just my 2 cents; if you reject on a "not found" but "not found" is an expected result I think it's better to resolve with a special "not found" value. Let promises fail on unexpected results so you can more easily differentiate the 2. Promises resolving in "not found" can follow the happy path but unexpected errors can follow the catch path. The question should be accompanied by the `checkValid...` function because I guess that's what your question is about. Should it reject if something not found. – HMR Jan 29 '18 at 02:53

2 Answers2

0
// Return a promise in which you inject true or false in the resolve value wheather the id exists or not
const validUserIdPromise = checkValidUserId(id)
  .then(() => true)
  .catch(() => false)

// same
const validCarIdPromise = checkValidCarId(id)
  .then(() => true)
  .catch(() => false)

// resolve both promises
Promise.all([validUserIdPromise, validCarIdPromise])
  .then(([validUser, validCar]) => { // Promise.all injects an array of values -> use destructuring
    console.log(validUser ? 'user id' : 'not user id')
    console.log(validCar ? 'car id' : 'not car id')
  })

/** Using async/await */

async function checkId(id) {
  const [validUser, validCar] = await Promise.all([validUserIdPromise, validCarIdPromise]);
  console.log(validUser ? 'user id' : 'not user id')
  console.log(validCar ? 'car id' : 'not car id')
}

checkId(id);
topheman
  • 7,422
  • 4
  • 24
  • 33
-1

You can return a resolved Promise from .catch(), pass both functions to Promise.all() then check the results at chained .then(), propagate an error at .then() if necessary

var validUserIdPromise = () => Promise.reject("not user id")
  .then(() => console.log("user id"))
  // handle error, return resolved `Promise`
  // optionally check the error type here an `throw` to reach
  // `.catch()` chained to `.then()` if any `Promise` is rejected
  .catch((err) => {console.error(err); return err});

var validCarIdPromise = () => Promise.reject("not car id")
  .then(() => console.log("car id"))
  // handle error, return resolved `Promise`
  .catch((err) => {console.error(err); return err});
  
Promise.all([validUserIdPromise(), validCarIdPromise()])
.then(response => {
  if (response[0] === "not user id" 
      && response[1] === "not car id") {
        console.log("both promises rejected")
      }
})
.catch(err => console.error(err));
guest271314
  • 1
  • 15
  • 104
  • 177
  • Promise.all rejects with the reason of the first promise that rejects. – Punith Jain Jan 28 '18 at 18:20
  • @PunithJain A chained `.catch()` handles the rejection – guest271314 Jan 28 '18 at 18:22
  • if the `validUserIdPromise()` promise is rejected why it is not going to catch in Promise.all? – Punith Jain Jan 28 '18 at 18:31
  • 1
    @PunithJain The rejection is _handled_ at the `.catch()` within the function. A value `return`ed from `.catch()` is a _resolved_ `Promise`, even if that value is an instance of `Error`. Both `.then()` and `.catch()` return a new `Promise` – guest271314 Jan 28 '18 at 18:32
  • @PunithJain See [Why is onRejected not called following Promise.all() where Promise.reject() included in array passed to Promise.all()?](https://stackoverflow.com/questions/35042068/why-is-onrejected-not-called-following-promise-all-where-promise-reject-incl) – guest271314 Jan 28 '18 at 18:53