Skip to content

Instantly share code, notes, and snippets.

@jthoms1
Created September 4, 2018 19:08
Show Gist options
  • Save jthoms1/04c4b308a5080f52dbfc316628e7579a to your computer and use it in GitHub Desktop.
Save jthoms1/04c4b308a5080f52dbfc316628e7579a to your computer and use it in GitHub Desktop.

Revisions

  1. jthoms1 created this gist Sep 4, 2018.
    24 changes: 24 additions & 0 deletions waterfall.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@

    function waterFallExec<T, S>(listOfItems: T[], func: (item: T) => Promise<S>): Promise<S[]> {
    const results: S[] = []
    return listOfItems.reduce(function (lastPromise, item) {
    return lastPromise.then(function (res) {
    return func(item).then(function (result) {
    res.push(result);
    return res;
    });
    });
    }, Promise.resolve(results));
    }



    const promiseOfResults = waterFallExec(['1', '2', '3'], (item) => {
    return Promise.resolve(
    parseInt(item, 10)
    );
    });

    promiseOfResults.then((results) => {
    console.log(results);
    })