loading
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Array.prototype.asyncForEach = async function (callback) {
  for (const index in this) {
    const element = this[index];
    // This will pause the execution of the code
    await callback(element, index, this);
  };
};

const waitFor = (ms) => new Promise(r => setTimeout(r, ms));
const getN = async n => n;

async function main() {
   [1, 2, 3].asyncForEach(async n => {
     await waitFor(1000);
     console.log(`main 'Array#asyncForEach' num=${n}`)
   })
}

main();

// Implementation by Jack on https://alligator.io/js/foreach-array-method/#asynchronous-foreach
// Array.prototype.asyncForEach = async function (callback) {
//   let k = 0;
//   while (k < this.length) {
//     if(!this[k])
//       return;
//     let element = this[k];
//     // This will pause the execution of the code
//     await callback(element, k, this);
//     k += 1;
//   };
// };