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

问题描述 投票:-1回答:2

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

javascript promise flow-control
2个回答
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
投票

您可以从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));
© www.soinside.com 2019 - 2024. All rights reserved.