Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda