diff --git a/README.md b/README.md index b778a14b2..6af096779 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ * [Redirect to url](#redirect-to-url) * [Reverse a string](#reverse-a-string) * [RGB to hexadecimal](#rgb-to-hexadecimal) +* [Run promises in series](#run-promises-in-series) * [Scroll to top](#scroll-to-top) * [Shuffle array values](#shuffle-array-values) * [Similarity between arrays](#similarity-between-arrays) @@ -459,6 +460,16 @@ const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6 // rgbToHex(255, 165, 1) -> 'ffa501' ``` +### Run promises in series + +Run an array of promises in series using `Array.reduce()` by creating a promise chain, where each promise returns the next promise when resolved. + +```js +const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); +// const delay = (d) => new Promise(r => setTimeout(r, d)) +// series([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete +``` + ### Scroll to top Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`. diff --git a/snippets/run-promises-in-series.md b/snippets/run-promises-in-series.md new file mode 100644 index 000000000..2193e8df4 --- /dev/null +++ b/snippets/run-promises-in-series.md @@ -0,0 +1,9 @@ +### Run promises in series + +Run an array of promises in series using `Array.reduce()` by creating a promise chain, where each promise returns the next promise when resolved. + +```js +const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); +// const delay = (d) => new Promise(r => setTimeout(r, d)) +// series([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete +```