Skip to content

Instantly share code, notes, and snippets.

@siewho
Forked from anvk/promises_reduce.js
Created October 30, 2021 02:31
Show Gist options
  • Select an option

  • Save siewho/8d692497f82a309eefe5ea9196c63cc0 to your computer and use it in GitHub Desktop.

Select an option

Save siewho/8d692497f82a309eefe5ea9196c63cc0 to your computer and use it in GitHub Desktop.

Revisions

  1. @anvk anvk renamed this gist May 26, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @anvk anvk created this gist May 26, 2016.
    22 changes: 22 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    function asyncFunc(e) {
    return new Promise((resolve, reject) => {
    setTimeout(() => resolve(e), e * 1000);
    });
    }

    const arr = [1, 2, 3];
    let final = [];

    function workMyCollection(arr) {
    return arr.reduce((promise, item) => {
    return promise
    .then((result) => {
    console.log(`item ${item}`);
    return asyncFunc(item).then(result => final.push(result));
    })
    .catch(console.error);
    }, Promise.resolve());
    }

    workMyCollection(arr)
    .then(() => console.log(`FINAL RESULT is ${final}`));