Merge pull request #61 from darrenscerri/promise-series
Add "Run promises in series"
This commit is contained in:
11
README.md
11
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`.
|
||||
|
||||
9
snippets/run-promises-in-series.md
Normal file
9
snippets/run-promises-in-series.md
Normal file
@ -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
|
||||
```
|
||||
Reference in New Issue
Block a user