简体   繁体   English

处理承诺链中的错误

[英]Handling errors in promise chains

There are two categories of errors that might occur in a promise chain. 在承诺链中可能会发生两类错误。

  1. Errors thrown from inside the promise chain (dealt with by .catch ) 从承诺链内部抛出的错误(使用.catch处理)
  2. Errors thrown when configuring the promise chain 配置承诺链时引发的错误

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM