Merge pull request #17137 from strapi/docs/improve-async-utils

This commit is contained in:
Marc Roig 2023-06-30 11:02:15 +02:00 committed by GitHub
commit f9bf60097c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -12,17 +12,64 @@ Async utils are grouping all function that interact with async stuff like Promis
## Detailed design
Available functions:
### mapAsync
- pipeAsync
- mapAsync
- reduceAsync
The `mapAsync` function is an asynchronous version of the `Array.prototype.map` method.
[See API reference](../../../api/api.mdx) (TODO)
Example usage:
```js
const input = [1, 2, 3];
const output = await mapAsync(input, async (item) => {
return item * 2;
});
console.log(output); // [2, 4, 6]
```
### reduceAsync
The `reduceAsync` function is an asynchronous version of the `Array.prototype.reduce` method.
Example usage:
```js
const input = [1, 2, 3];
const reducer = reduceAsync(input);
const output = await reducer(async (accumulator, item) => {
return accumulator + item;
}, 0);
console.log(output); // 6
```
### pipeAsync
The `pipeAsync` function is a utility function for composing asynchronous functions. It takes a list of functions as input, and returns a new function that applies each function in turn to the input.
Example usage:
```js
async function addOne(input: number): Promise<number> {
return input + 1;
}
async function double(input: number): Promise<number> {
return input * 2;
}
const addOneAndDouble = pipeAsync(addOne, double);
const output = await addOneAndDouble(3);
console.log(output); // 8
```
### When to use
Everytime the code has to act with promises and iterate other them, an async utils function should be used.
Every time the code has to act with promises and iterate other them, an async utils function should be used.
### Should I add my function here ?
@ -32,6 +79,12 @@ Please consider the next point if a lots of functions are available in the async
## Potential improvements
Some ideas of functions that could be added:
- Other `Array.prototype` methods: `filterAsync`, `someAsync`, `everyAsync`, `findAsync`, `findIndexAsync`, `flatMapAsync`.
- `retryAsync`: A function that retries an asynchronous operation a specified number of times if it fails. It takes an asynchronous operation and a number of retries as input, and returns the result of the operation if it succeeds within the specified number of retries, or throws an error if it fails after all retries.
- `timeoutAsync`: A function that adds a timeout to an asynchronous operation. It takes an asynchronous operation and a timeout duration as input, and returns the result of the operation if it completes within the specified timeout, or throws an error if it takes longer than the timeout.
If we begin to use lots of async utils function, we may consider to migrate to a specialized library like [asyncjs](http://caolan.github.io/async/v3/)
## Resources