我正在寻找一种更简单/更简单的方法来创建错误函数,我只是在寻找一种退出 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/