异步foreach forAsyncEach

97 阅读1分钟

2024.01.04

Array.prototype.forAsyncEach = async function (callback) {
  for (let i = 0; i < this.length; i++) {
    this[i] = await callback(this[i], i, this);
    if (i == this.length-1) {
      return this
    }
  }
};

async function start() {
  const arr = [1, 2, 3, 4, 5];
  await arr.forAsyncEach(async (element, index, array) => {
    return await new Promise(resolve => setTimeout(resolve(element * 2), 1000));
  }).then(ok=>console.log(ok)/* [ 2, 4, 6, 8, 10 ] */)
  console.log('arr', arr) /* [ 2, 4, 6, 8, 10 ] */
}
start()