Skip to content

Instantly share code, notes, and snippets.

@dalaidunc
Created August 25, 2017 15:23
Show Gist options
  • Save dalaidunc/14b9110cff8df876d6cdf4815774f706 to your computer and use it in GitHub Desktop.
Save dalaidunc/14b9110cff8df876d6cdf4815774f706 to your computer and use it in GitHub Desktop.

Revisions

  1. dalaidunc created this gist Aug 25, 2017.
    18 changes: 18 additions & 0 deletions asyncForEach.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    // extend the Array prototype with an asyncForEach method
    Array.prototype.asyncForEach = async function (fn) {
    for (let i = 0; i < this.length; i++) {
    await fn(this[i], i);
    }
    };

    const arr = ['a', 'b', 'c', 'd'];

    // define a Promise wrapper around the setTimeout function
    function wait (fn, time) {
    return new Promise(resolve => setTimeout(() => {fn();resolve();}, time));
    }

    // call an asynchronous function upon each element in the array
    arr.asyncForEach(async (item, index) => {
    await wait(() => console.log(item), 500);
    });