Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
Is there a way to work with Javascript Promise in following function?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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().

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!