Last active
September 11, 2018 22:23
-
-
Save scwood/e282891cc628f5f7cf9b250ec620331a to your computer and use it in GitHub Desktop.
chunking promise.all and capturing all the promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const chunkAsync = (arr, callback, chunkSize = 1) => { | |
| const results = [] | |
| const chunks = chunkArray(arr, chunkSize) | |
| const work = chunks.reduce((previousPromise, chunk) => { | |
| return previousPromise.finally(() => { | |
| results.push(...chunk.map(callback)) | |
| return Promise.all(results) | |
| }) | |
| }, Promise.resolve()) | |
| return work.finally(() => results) | |
| } | |
| const chunkArray = (arr, chunkSize) => { | |
| const result = [] | |
| for (let i = 0; i < arr.length; i += chunkSize) { | |
| result.push(arr.slice(i, i + chunkSize)) | |
| } | |
| return result | |
| } | |
| // Example | |
| const stuff = [1, 2, 3, 4, 5] | |
| const doAsyncWork = (i) => { | |
| return new Promise((resolve) => { | |
| console.log(`starting ${i}...`) | |
| setTimeout(() => { | |
| console.log(`...finished ${i}`) | |
| resolve(i) | |
| }, 1000) | |
| }) | |
| } | |
| chunkAsync(stuff, doAsyncWork, 2).then((result) => console.log(result)) | |
| // starting 1... | |
| // starting 2... | |
| // ...finished 1 | |
| // ...finished 2 | |
| // starting 3... | |
| // starting 4... | |
| // ...finished 3 | |
| // ...finished 4 | |
| // starting 5... | |
| // ...finished 5 | |
| // [ Promise { 1 }, | |
| // Promise { 2 }, | |
| // Promise { 3 }, | |
| // Promise { 4 }, | |
| // Promise { 5 } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment