简体   繁体   中英

How to catch errors in a sequential promise chain

I'm building a synchronous series of Promises like so:

let order = [fn1, fn2, fn3];
let result = Promise.resolve();
order.reduce((chain, task) => {
    return chain.then(task);
}, result);

(via the 'Executing Promises in Series' section of this article ). This runs everything in series like I'd expect, but having issues with catching errors/where to put the catch block.

Just put it at the end, where you'd normally continue with the chain as well:

[fn1, fn2, fn3].reduce((chain, task) => {
    return chain.then(task);
}, Promise.resolve()).catch(err => {
    console.error(err);
});

Remember that the reduce expands to

Promise.resolve().then(fn1).then(fn2).then(fn3).catch(err => {
    console.error(err);
});

You don't necessarily need a catch block. The reduce will return the first rejected promise in the chain. To see this, write out what the reduce will actually produce:

const resolve = () => Promise.resolve(), reject = () => Promise.reject();
const promises = [resolve, reject, resolve];

const result = Promise.resolve()
   .then(resolve).then(reject).then(resolve);

The first then handler will be invoked, resulting in a fulfilled promise, so the next then handler will be invoked, this time resulting in a rejected promise, so the final then will not invoke its handler and will "pass through" the rejected promise, which will become the result of the entire expression, and which you can catch with

result.catch(() => alert("Hey Mom, one of the chained promises rejected"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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