执行一个 promise 循环并捕获过程中的错误

Execute a promise loop and catch errors along the way

所以这是来自@Roamer-1888 的真正美女:

executePromiseLoop(myArray).catch(logError).then(() => console.log('yay!'));

function executePromiseLoop(arr) {
    return arr.reduce(function(promise, email) {
        return promise.then(function() {
            return myCustomPromise(email);
        });
    }, Promise.resolve());
}

这是一个串行执行的承诺循环。我有两个顾虑:

  1. 如果循环中的 promise 失败会发生什么,它会退出循环吗?
  2. 我应该在循环内实现捕获,还是将失败传播回调用函数?

我应该在循环中插入一个 catch 吗?

function executePromiseLoop(arr) {
    return arr.reduce(function(promise, email) {
        return promise.catch(logError).then(function() {
            return myCustomPromise(email);
        });
    }, Promise.resolve());
}

What happens if a promise in the loop fails, does it quit the loop?

是的。如果一个 promise 被拒绝,接下来的所有 promise 都不会被执行。例如,请参阅此代码:

Promise.resolve()
  .then(Promise.reject)
  .then(() => console.log('this will not be executed'))
  .catch(() => console.log('error'))

第三行的promise不会被执行,因为之前的promise被拒绝了

Should I implement a catch inside the loop, or will a fail propagate back up to the calling function?

拒绝消息会传播,因此您不需要在循环内使用 catch。例如,请参阅此代码:

Promise.resolve()
  .then(() => Promise.resolve())
  .then(() => Promise.reject('something went wrong'))
  .then(() => Promise.resolve())
  .then(() => Promise.resolve())
  .catch(error => console.log(error))