1.支持async func
为避免callback hell,通常会将异步函数以promise进行包装,而原生的forEach不支持async func,这里给出一个支持async func的forEach实现(非原创):
//async/await
const CustomForeach = async (arr, callback) => {
return new Promise(async function (resolve, reject) {
const length = arr.length;
const O = Object(arr);
let k = 0;
while (k < length) {
if (k in O) {
const kValue = O[k];
await callback(kValue, k, O);
}
k++;
}
resolve();
});
};
2.支持async func且并行
上文的实现支持async func但串行执行,更常见的场景是需要并行执行,于是结合async库的parallel给出以下并行的实现:
//async/await with parallel @author windroid
const CustomForeachParallel = async (arr, callback) => {
return new Promise(async function (resolve, reject) {
const length = arr.length;
const O = Object(arr);
let k = 0;
var funcArr = new Array();
while (k < length) {
if (k in O) {
const kValue = O[k];
((value, index) => {
funcArr[k] = (parallelcb) => {
callback(value, index, O).then((ret)=>{
return parallelcb(null, index);
}).catch((err)=>{
return parallelcb(err, index);
});
}
})(kValue, k);
}
k++;
}
async.parallel(funcArr, function (err, resp){
if(err) return reject(err);
resolve(resp);
});
});
};