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 filter 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 call filter with an async function.
For instance, we write
const results = await filter(myArray, async (num) => {
await doAsyncStuff();
return num > 2;
});
to call filter with myArray and an async function which always returns a promise.
An array of promises after filtering is done is returned.
Then we use await to get the array of promise results and assign the results to results.
Conclusion
To filter an array with a function that returns a promise with JavaScript, we call filter with an async function.