javascript - 使用自定义错误退出/违背 promise

标签 javascript promise bluebird

我正在寻找一种更简单/更简单的方法来创建错误函数,我只是在寻找一种退出 promise 链的简单方法。下面您可以看到一个错误对象 NoUserFound 和一个 promise 链。我正在寻找的期望结果是,当 model.readUserAddresses 返回 false 时,我会抛出一个特定的错误来跳过 promise 链。是否有一种更简单、更直接(单行)的方法来为此目的创建 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/

相关文章:

javascript - 将多个参数传递给 Promise 函数?

javascript - NodeJS 中的嵌套 Promise

javascript - 一键发送两个表单,然后重定向到第三个操作

javascript - 使用中点圆算法生成实心圆的点

node.js - 调用 "then"时 Promise 挂起

javascript - Node 中的 Bluebird.js 和异步 api 调用

javascript - 使用 Promise 从映射函数内部推送到外部对象

javascript - 一些网站不接受将 javascript 注入(inject)到 webview 中

javascript - node的微服务架构会不会降低效率,增加响应时间?有什么解决办法还是我的理解有误?

javascript - 使用 BlueBird.Promisify 时,未捕获的 typeError 中间值不是函数