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

174
Views
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
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!