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

175
Visualizações
How to stop response before all the code is executed, using async await

I have a function named getActiveUsers which helps me to find active users

const getActiveUsers = async (req, res) => {
let results = [];

const rewards = await Reward.find().distinct('data');

await rewards.map(async (reward) => {
    const result = await Callback.findOne({
        data: reward,
    });
    results.push(result);
});

return res
    .status(400)
    .json({ success: true, count: results.length, data: results })};

I first want to get data from Reward collection, which will return 100 records to rewards array. After waiting for all the results, I want to go through the retrieved array(rewards) one by one, and get data from another collection called Callback. And this data will be pushed to another array called results one by one.(I have used a map function for that) After awaiting for all 100 records to results array, I want to send it as the response. But unfortunately, my code does not wait for the map function. It send response as a empty array(results). And later runs the map and pushes elements to results array. Please help me fix this by using async/await only. If it is not possible, give me the best solution.

about 4 years ago · Juan Pablo Isaza
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