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

150
Views
How do i change the Aysnc loop code to promises

kindly please help me with task. i have to convert this logic by using promises

loadUsers(userIds, load, done) {
   const users = [];
     let numberOfLoadedUsers = 0;
     userIds.forEach((userId, index) =>
       load(userId, function (user) {
         users[index] = user;
         numberOfLoadedUsers += 1;
         if (numberOfLoadedUsers === userIds.length) {
           done(users);
         }
      })
    ); 
 }
 module.exports = loadUsers;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I believe what you want is to change the callback in load() to a Promise based API. While changing load() to use promises is rather simple, there are some others changes in your code necessary to make that work as you would expect it to work some of which are described in this blog post. See this version using promises and some explanatory comments.

async function loadUsers(userIds, load, done) {
    const users = [];
    let numberOfLoadedUsers = 0;
    // in order to use await in callback function must be "async"
    // now you must change from "forEach" to "map" as every callback now returns a promise and forEach does not return anything
    const promises = userIds.map(async (userId, index) => {
        const user = await load(userId);
        users[index] = user;
        numberOfLoadedUsers += 1;
        // to show you it is working
        console.log(user, index);
        if (numberOfLoadedUsers === userIds.length) {
            done(users);
        }
    });

    // promises is now an array of promises (one for each item)
    // you must wait until all promises resolve and can then return
    await Promise.all(promises);
    console.log("all users loaded.")
}

// POJ(S)O
class User {
    constructor(id, name) {
        this._id = id;
        this._name = name;
    }
}

async function load(userId) {
    // you must return a Promise in order to make it an asynchronous function
    return new Promise((resolve, reject) => {
        try {
            // load your user here (e.g. HTTP request, read from file etc.)
            const loadedUser = new User(userId, `Testuser-${userId}`)
            // user was successfully loaded -> resolve promise
            resolve(loadedUser)
        } catch (error) {
            // some error occured -> reject promise
            reject(error)
        }
    })
}

function done(){
    console.log("done() called");
}


const userIds = [1, 2, 3];
// test
(async () => {
    await loadUsers(userIds, load, done)
})();

Expected output:

User { _id: 1, _name: 'Testuser-1' } 0
User { _id: 2, _name: 'Testuser-2' } 1
User { _id: 3, _name: 'Testuser-3' } 2
done() called
all users loaded.
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!