我有一个promise数组,我用Promise.all(arrayOfPromises)来解析它;

我继续承诺链。大概是这样的

existingPromiseChain = existingPromiseChain.then(function() {
  var arrayOfPromises = state.routes.map(function(route){
    return route.handler.promiseHandler();
  });
  return Promise.all(arrayOfPromises)
});

existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
  // do stuff with my array of resolved promises, eventually ending with a res.send();
});

我想添加一个catch语句来处理一个单独的promise,以防它出错,但是当我尝试时,promise。all返回它找到的第一个错误(忽略其余的错误),然后我就不能从数组中的其余承诺(没有错误)中获得数据。

我试过做一些像…

existingPromiseChain = existingPromiseChain.then(function() {
      var arrayOfPromises = state.routes.map(function(route){
        return route.handler.promiseHandler()
          .then(function(data) {
             return data;
          })
          .catch(function(err) {
             return err
          });
      });
      return Promise.all(arrayOfPromises)
    });

existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
      // do stuff with my array of resolved promises, eventually ending with a res.send();
});

但这并不能解决问题。

谢谢!

--

编辑:

下面的答案是完全正确的,代码被破坏是由于其他原因。如果有人感兴趣,这是我最终得出的解决方案……

节点快速服务器链

serverSidePromiseChain
    .then(function(AppRouter) {
        var arrayOfPromises = state.routes.map(function(route) {
            return route.async();
        });
        Promise.all(arrayOfPromises)
            .catch(function(err) {
                // log that I have an error, return the entire array;
                console.log('A promise failed to resolve', err);
                return arrayOfPromises;
            })
            .then(function(arrayOfPromises) {
                // full array of resolved promises;
            })
    };

API调用(路由。异步调用)

return async()
    .then(function(result) {
        // dispatch a success
        return result;
    })
    .catch(function(err) {
        // dispatch a failure and throw error
        throw err;
    });

把。catch作为承诺。在.then之前的所有内容似乎都用于从原始的promise中捕获任何错误,但随后将整个数组返回到下一个.then

谢谢!


当前回答

对于那些使用ES8的人来说,你可以使用异步函数做如下的事情:

var arrayOfPromises = state.routes.map(async function(route){
  try {
    return await route.handler.promiseHandler();
  } catch(e) {
    // Do something to handle the error.
    // Errored promises will return whatever you return here (undefined if you don't return anything).
  }
});

var resolvedPromises = await Promise.all(arrayOfPromises);

其他回答

Promise.allSettled

而不是承诺。都使用Promise。等待所有承诺的解决,不管结果如何

let p1 = new Promise(resolve => resolve("result1")); let p2 = new Promise((resolve,reject) => reject('some trouble ')); let p3 = new Promise(resolve => resolve("result3")); //返回每个promise状态和值的信息 Promise.allSettled ((p1, p2, p3))。然后(结果= > console.log(结果));

Polyfill

if (! promise . allsettle) { const rejectHandler = reason => ({status: 'rejected', reason}); const resolveHandler = value =>({状态:'已完成',value}); 的承诺。allsettle =函数(承诺){ const convertedPromises = promises .map(p =>承诺。resolve(p)。然后(resolveHandler rejectHandler)); 返回Promise.all (convertedPromises); }; }

你总是可以用一种方式来包装你的promise返回函数,让它们捕获失败并返回一个一致的值(例如error.message),这样异常就不会一直滚到promise。所有功能和禁用它。

async function resetCache(ip) {

    try {

        const response = await axios.get(`http://${ip}/resetcache`);
        return response;

    }catch (e) {

        return {status: 'failure', reason: 'e.message'};
    }

}

在allsettle的帮助下,我们现在可以读取的状态 每个承诺都是,并单独处理每个错误,而不会丢失任何关键信息

const promises = [
    fetch('/api/first'), // first
    fetch('/api/second') // second
];

最简单的方法是处理错误

const [firstResult, secondResult] = await Promise.allSettled(promises)


 // Process first
 if (firstResult.status === 'rejected') {
   const err = firstResult.reason
   // Here you can handle error
 } else {
   const first = firstResult.value
 }

  // Process second
 if (secondResult.status === 'rejected') {
   const err = secondResult.reason
   // Here you can handle error
 } else {
   const second = secondResult.value
 }

处理错误的好方法

const results = await Promise.allSettled(promises);
const [first, second] = handleResults(results)


function handleResults(results) {
  const errors = results.filter(result => result.status === 'rejected').map(result => result.reason)

  if (errors.length) {
    // Aggregate all errors into one
    throw new AggregateError(errors)
  }

  return results.map(result => result.value)
}

或者,如果你有这样的情况,当有一个失败时,你并不特别关心已解决的承诺的值,但你仍然希望它们运行,你可以这样做,当它们都成功时,你会正常地解决承诺,当它们中的任何一个失败时,你会拒绝失败的承诺:

function promiseNoReallyAll (promises) {
  return new Promise(
    async (resolve, reject) => {
      const failedPromises = []

      const successfulPromises = await Promise.all(
        promises.map(
          promise => promise.catch(error => {
            failedPromises.push(error)
          })
        )
      )

      if (failedPromises.length) {
        reject(failedPromises)
      } else {
        resolve(successfulPromises)
      }
    }
  )
}

ES2020为Promise类型引入了新的方法:Promise. allsettle()。

的承诺。当所有输入承诺都已解决时,allsettle会给你一个信号,这意味着它们要么被满足,要么被拒绝。这在不关心承诺状态的情况下很有用,您只想知道工作何时完成,而不管它是否成功。

异步函数(){ Const promises = [ Fetch ('/api.stackexchange.com/2.2'), //成功 Fetch ('/this-will-fail') //失败 ]; const result = await promise . allsettle (promises); console.log(结果。Map (promise => promise.status)); // [' completed ', 'rejected'] }

详见v8博客文章。