定义foreach函数 支持异步

70 阅读1分钟
//自定义foreach函数  支持异步
Array.prototype.myforeach = async function(callback,thisArg){
  const _arr = this,
  _isArray = Array.isArray(_arr),
  _thisArg = thisArg?Object(thisArg):window //回调函数的this指向
  if(!_isArray){
    throw new TypeError("the caller of myforeach must be the type 'Array'")
  }
 for(let i= 0;i<_arr.length;i++){
   await callback.call(_thisArg,_arr[i])
 }
}

const arr = [fn,fn,fn]
arr.myforeach(async(fn)=>{
  await fn()
})