我正在寻找一种创建错误函数的更简单方法,我只是在寻找一种退出承诺链的简单方法。在下面,您可以看到一个错误对象NoUserFound和一个Promise链。我要寻找的期望结果是model.readUserAddresses返回false时,我抛出特定错误以跳过承诺链。有没有更简单,更直接的方法(单行)来创建NoUserFound自定义错误呢?

function NoUserFound(value) {
   Error.captureStackTrace(this);
   this.value = value;
   this.name = "NoUserFound";
}
NoUserFound.prototype = Object.create(Error.prototype);

model.readUserAddresses(email)
  .then(ifFalseThrow(NoUserFound))
  .then(prepDbCustomer)
  .then(shopify.customerCreate)
  .catch(NoUserFound, () => false)


理想情况下,我可以做这样的事情。

model.readUserAddresses(email)
  .then(ifFalseThrow('NoUserFound'))
  .then(prepDbCustomer)
  .then(shopify.customerCreate)
  .catch('NoUserFound', () => false)


并且不必具有无用的一次性错误类。

最佳答案

如果您不想建立自己的错误类,也可以使用Bluebird's builtin error types之一,即OperationalError

model.readUserAddresses(email)
  .then(ifFalseThrow(Promise.OperationalError))
  .then(prepDbCustomer)
  .then(shopify.customerCreate)
  .error(() => false)




如果这不符合您的需求(例如,由于OperationalError已经用于其他用途),则实际上根本不必使其成为自定义错误类型(子类)。 catch也采用简单的谓词功能,因此您可以使用

model.readUserAddresses(email)
  .then(ifFalseThrow(Error, "noUserFound"))
  .then(prepDbCustomer)
  .then(shopify.customerCreate)
  .catch(e => e.message == "noUserFound", () => false)




最后但并非最不重要的一点是,如果只想跳过一部分链,则抛出异常不是最好的主意。明确地分支:

model.readUserAddresses(email)
  .then(userAddresses =>
     userAddresses
       ? prepDbCustomer(userAddresses)
         .then(shopify.customerCreate)
       : false
  )


(并酌情缩短该回调,例如.then(u => u && prepDbCustomer(u).then(shopify.customerCreate))

关于javascript - 使用自定义错误退出/违反 promise ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36075094/

10-11 22:22
查看更多