我想说我想对一个对象的每个值执行一个函数。
如何捕获迭代结束并知道没有错误在每个值上运行函数?
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
});
答案 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));