Home > OS >  How can I pass async callback function in Array.filter?
How can I pass async callback function in Array.filter?

Time:07-14

I need to get check that given zone exists or not through "getOneParkingZone" function. Can anyone suggest a better way to do this and also explain what this is not working?

 let result = Array.filter(async (zone) =>{
           const checkZone = await getOneParkingZone({id: zone.id})
           return checkZone ? true : false ;
       }));

CodePudding user response:

You need to resolve the promises first, then you can filter them.

Ex:

const ids = [1, 2, 3, 4]


const resolvedPromises = await Promise.all(ids.map(id => getOneParkingZone({id})))

const result = resolvedPromises.filter(item => item)

CodePudding user response:

filter needs the callback function to return a truthy or falsy value.

Your callback function returns a promise that resolves to true or false which will always be a truthy value.


Map the array to get the data you need, wait for the promises to resolve, then deal with the new values.

const baseArray = [/*...*/]
const arrayOfPromises = baseArray.map(
    async (value) => ({
        ...value, 
        checkZone: await getOneParkingZone({id: zone.id}) 
    }
);
const arrayWithCheckZone = await Promise.all(arrayOfPromises);
const filteredArray = arrayWithCheckZone.filter(value => value.checkZone);
const filteredArrayWithoutCheckZone = 
    filteredArray.map(value => {
        const { checkZone, ...rest } = value;
        return rest;
    });
);

Or without the extra variables:

(await Promise.all([/*...*/].map(
    async (value) => ({
        ...value, 
        checkZone: await getOneParkingZone({id: zone.id}) 
    }
))).filter(value => value.checkZone).map(value => {
        const { checkZone, ...rest } = value;
        return rest;
    });
);
  • Related