Rename js snippets
This commit is contained in:
40
snippets/js/s/chain-async-functions.md
Normal file
40
snippets/js/s/chain-async-functions.md
Normal file
@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Chain async functions
|
||||
type: snippet
|
||||
language: javascript
|
||||
tags: [function]
|
||||
cover: tram-car
|
||||
dateModified: 2020-09-15T16:28:04+03:00
|
||||
---
|
||||
|
||||
Chains asynchronous functions.
|
||||
|
||||
- Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
||||
|
||||
```js
|
||||
const chainAsync = fns => {
|
||||
let curr = 0;
|
||||
const last = fns[fns.length - 1];
|
||||
const next = () => {
|
||||
const fn = fns[curr++];
|
||||
fn === last ? fn() : fn(next);
|
||||
};
|
||||
next();
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
chainAsync([
|
||||
next => {
|
||||
console.log('0 seconds');
|
||||
setTimeout(next, 1000);
|
||||
},
|
||||
next => {
|
||||
console.log('1 second');
|
||||
setTimeout(next, 1000);
|
||||
},
|
||||
() => {
|
||||
console.log('2 second');
|
||||
}
|
||||
]);
|
||||
```
|
||||
Reference in New Issue
Block a user