JavaScript Promise - 多个 promise 失败时的逻辑

JavaScript Promise - logic when multiple promises fail

如果一组 Promise 被拒绝(全部),我如何应用逻辑?

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");

扩展我的问题:是否建议使用 Promise.reject() 来控制 JavaScript 应用程序的正常流量,还是仅在出现问题时才使用它?

用例:我的 nodeJs 应用程序从客户端接收一个 uuid,并根据匹配的资源(示例中的用户或汽车)进行响应。

您可以 return 从 .catch() 解析 Promise,将两个函数传递给 Promise.all(),然后检查链式 .then() 的结果,传播错误如有必要,在 .then()

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));

// 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);