January 2020
Intermediate to advanced
470 pages
11h 13m
English
Filtering with an async function is a tad more complicated. We will have to use mapAsync() to produce an array of true/false values, and then use the standard filter() method to pick values out of the original array depending on what the async filtering function returned. Let's try out a simple example, calling the API and accepting only even results by means of a fakeFilter() function, which, for our example, accepts even numbers and rejects odd ones:
const filterAsync = (arr, fn) => mapAsync(arr, fn).then(arr2 => arr.filter((v, i) => Boolean(arr2[i])));const fakeFilter = (value) => new Promise(resolve => setTimeout(() => resolve(value % 2 === 0), 1000) );(async () => { console.log("START FILTER"); const filtered ...