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

时间:2018-01-28 18:05:37

标签: javascript promise flow-control

如果一组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 app从客户端接收uuid,并根据匹配的资源(示例中的用户或汽车)进行响应。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:-1)

您可以从Promise返回已解决的.catch(),将这两个函数传递给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));