[英]Handling errors in promise chains
There are two categories of errors that might occur in a promise chain. 在承诺链中可能会发生两类错误。
.catch
) .catch
处理) My question is how best to deal with the latter. 我的问题是如何最好地应对后者。
For example, in the following .catch
will not catch exceptions thrown by foo
before it has had a chance to return a promise. 例如,下面的
.catch
不会捕获foo
有机会返回诺言之前抛出的异常。
function go() {
return foo()
.then(bar)
.catch(bam);
}
Clearly I can wrap the contents of go
in a try-catch
block. 显然,我可以将
go
的内容包装在try-catch
块中。
But would it be better to return an immediately rejected promise from a catch block in foo
to "maintain the API" and have a promise-based interface for all eventualities? 但是,从
foo
的catch块返回立即被拒绝的诺言以“维护API”并为所有可能的事件提供基于诺言的接口会更好吗?
Alternatively, you can include foo
in the chain, like this 或者,您可以在链中包括
foo
,如下所示
Promise.resolve()
.then(foo)
.then(bar)
.catch(bam);
Now, even if the foo
throws, the bam
will take care of it. 现在,即使
foo
抛出了, bam
也会照顾它。
Or, build a wrapper over foo
, 或者,在
foo
构建包装器,
function promiseWrapper(func) {
try {
return Promise.resolve(func());
} catch (e) {
return Promise.reject(e);
}
}
And then use it, instead of foo
, like this 然后使用它,而不是
foo
,就像这样
function go() {
return promiseWrapper(foo)
.then(bar)
.catch(bam);
}
Or you can be more explicit and do: 或者,您可以更明确地执行以下操作:
function foo() {
try {
// some staff which should return promise
}
catch(e) {
retrun Propmise.reject('the reason');
}
}
then use 然后使用
function go() {
return foo()
.then(bar)
.catch(bam);
}
Now, you don't need to change all usages of your foo
. 现在,您无需更改
foo
所有用法。
Use the proposed (Stage 3) async
functions. 使用建议的(第3阶段)
async
功能。 They are guaranteed to return a promise, so you don't have to worry about capturing synchronous exceptions while setting up the promise chain. 他们保证返回承诺,因此您不必担心在设置承诺链时捕获同步异常。
(async () => {throw new Error})().catch(::console.error)
You can promisify foo
so that any error happens within foo
triggers reject function automatically. 您可以承诺
foo
以便在foo
触发器内自动发生任何错误都会触发拒绝函数。 Such as; 如;
function foo(){ throw new Error("booom"); return Promise.resolve(42); } function bar(v) { console.log("I am resolved with " + v())} function baz(v) { console.log("I am rejeceted because of a " + v)} function go() { Promise.resolve(foo) .then(bar) .catch(baz); } go();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.