对象映射:Promise.all捕获迭代结束和错误

时间:2018-03-28 05:08:59

标签: javascript

我想说我想对一个对象的每个值执行一个函数。

如何捕获迭代结束并知道没有错误在每个值上运行函数?

Object.keys(result).map(function(key, index) {
  var value = result[key];

  functiontorun(value, (result, error) => {
     if (error) {
     // catch the error
     }
  });

  // AT THE END OF THE ITERATION               
     // if no error at all => then something
     // if at least one error => then something else


});

1 个答案:

答案 0 :(得分:3)

将每个请求转换为承诺,并在结果上使用Promise.all

const allPromises = Object.keys(result).map(function(key, index) {
  var value = result[key];
  return new Promise((resolve, reject) => {
    functiontorun(value, (result, error) => {
      if (error) {
        // catch the error
        reject(error);
      } else resolve();
    });
  });
});
Promise.all(allPromises)
  .then(() => console.log('all successful'))
  .catch(err => console.log('at least one error ' + err));