Home > Software engineering >  Is there a way to work with Javascript Promise in following function?
Is there a way to work with Javascript Promise in following function?

Time:03-07

So I have the following piece of code in javascript

async function getFoodData (req, res) {
    const ids = req.body.data;
    const food = [];
    ids.map((id) => {
        Food.findOne({ _id: id },(err, result) => {
            if(result){
                food.push(result)
            } 
        })
    })
    return res.status(200).json({ Food: food })
}

The ids are a bunch of Mongo Id's received in the body This function looks for data and on returning results it adds it into the food array. However, the return statement runs first and I get an empty array. I think my problem will be solved by using Promises but I am new to the concept and hence can someone help me with it.

CodePudding user response:

You can make use of await and Promise.all to achieve this.

Promise.all() takes an array of promises. Now with the statement, await Promise.all(foodPromises); you are waiting for all the promises to be resolved.

After that you can filter out the result array for only truthy values, which you were doing in your code.

async function getFoodData (req, res) {
    const ids = req.body.data;
    const food = [];
    const foodPromises = ids.map((id) => 
        Food.findOne({ _id: id }));
    await Promise.all(foodPromises);
    let returnData = foodPromises.filter(x => x);
    return res.status(200).json({ Food: food })
}

.map() is usually used when you want to transform an array into another. If you just want to run a loop use for/forEach().

CodePudding user response:

After some research, I also found another solution

async function getFoodData (req, res) {
    const ids = req.body.data;
    const food = [];
    async function foodData(id) {
        const food = await Food.findOne({ _id: id })
            if(food) return food
    } 
    for( let i = 0; i < ids.length; i   ) {
        const result = await foodData(ids[i])
        if(result) food.push(result)
    }
    return res.status(200).json({ Food: food })
}    

Creating a function and then using await while looping did the work for me

  • Related