There are two categories of errors that might occur in a promise chain.
.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.
function go() {
return foo()
.then(bar)
.catch(bam);
}
Clearly I can wrap the contents of go
in a try-catch
block.
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?
答案 0 :(得分:1)
或者,您可以在链中加入foo
,例如
Promise.resolve()
.then(foo)
.then(bar)
.catch(bam);
现在,即使foo
投掷,bam
也会照顾它。
或者,在foo
上构建一个包装器,
function promiseWrapper(func) {
try {
return Promise.resolve(func());
} catch (e) {
return Promise.reject(e);
}
}
然后使用它,而不是foo
,就像这样
function go() {
return promiseWrapper(foo)
.then(bar)
.catch(bam);
}
答案 1 :(得分:1)
或者你可以更明确地做:
function foo() {
try {
// some staff which should return promise
}
catch(e) {
retrun Propmise.reject('the reason');
}
}
然后使用
function go() {
return foo()
.then(bar)
.catch(bam);
}
现在,您无需更改foo
的所有用法。
答案 2 :(得分:1)
使用建议的(第3阶段)async
函数。他们保证会返回承诺,因此您不必担心在设置承诺链时捕获同步异常。
(async () => {throw new Error})().catch(::console.error)
答案 3 :(得分:0)
您可以宣传foo
,以便foo
内的任何错误都会自动触发拒绝功能。如;
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();