Sometimes, we want to filter an array with a function that returns a promise with JavaScript.
In this article, we’ll look at how to filter an array with a function that returns a promise with JavaScript.
How to filtering an array with a function that returns a promise with JavaScript?
To filter an array with a function that returns a promise with JavaScript, we can use the Promise.all
method with the array filter
method.
For instance, we write
const filterPromise = async (values, fn) => {
const booleans = await Promise.all(values.map(fn));
const filtered = values.filter((_, i) => booleans[i]);
return filtered;
};
to define the filterPromise
function.
In it, we call Promise.all
with an array of promises we get from values.map(fn)
.
Then we call values.filter
with a callback that returns an array of filtered values according to the values of booleans[i]
.
Conclusion
To filter an array with a function that returns a promise with JavaScript, we can use the Promise.all
method with the array filter
method.