Merge pull request #61 from darrenscerri/promise-series

Add "Run promises in series"
This commit is contained in:
Angelos Chalaris
2017-12-13 11:59:32 +02:00
committed by GitHub
2 changed files with 20 additions and 0 deletions

View File

@ -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`.

View 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
```