JavaScript 承诺 - 多个承诺失败时的逻辑



如果一组承诺被拒绝(全部(如何应用逻辑?

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 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);
你可以

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

相关内容

  • 没有找到相关文章

最新更新