Last active
February 24, 2019 17:56
-
-
Save kouks/266888695364f82dec0f149ce6128407 to your computer and use it in GitHub Desktop.
Resolve an array of JS promises one after another - one liner
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
| // Example data. | |
| const data = [1, 2, 3] | |
| const fn = async a => a * a | |
| // If we care about errors. | |
| data.reduce((carry, item) => carry.then(() => fn(item)), Promise.resolve()) | |
| .catch(console.error) | |
| .then(() => { ... }) | |
| // If we don't care. | |
| data.reduce((carry, item) => carry.then(() => fn(item), () => {}), Promise.resolve()) | |
| .then(() => { ... }) | |
| // You can also pass the argument around. | |
| data.reduce((carry, item) => carry.then(res => fn(res + item)), Promise.resolve(1)) | |
| .then(res => { ... }) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment