Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda