Add run-promises-in-series
This commit is contained in:
13
README.md
13
README.md
@ -44,6 +44,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)
|
||||
@ -240,7 +241,7 @@ Use `reduce()` to get all elements inside the array and `concat()` to flatten th
|
||||
|
||||
```js
|
||||
const flatten = arr => arr.reduce( (a, v) => a.concat(v), []);
|
||||
// flatten([1,[2],3,4) -> [1,2,3,4]
|
||||
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||
```
|
||||
|
||||
### Get max value from array
|
||||
@ -422,6 +423,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
|
||||
var series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
||||
// var 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
|
||||
var series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
||||
// var 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