12

I am currently waiting for all the promise to finish sequentially like this:

(async() => {
  let profile = await profileHelper.getUserData(username);
   let token = await tokenHelper.getUserToken(username);
   console.log(profile);
   console.log(token);
   return {profile: profile, token: token};
})();

But this way, profile and token executes sequentially. Since both are independent of each other, I want both of them to be executed independently together. I think this can be done using Promise.all, but I am not sure of the syntax and I could not find any help as well.

So my question is how I can convert above api calls to run together and then return the final output.

undefined
  • 3,464
  • 11
  • 48
  • 90

4 Answers4

22
(async() => {
  const [ profile, token ] = await Promise.all([
    profileHelper.getUserData(username),
    tokenHelper.getUserToken(username)
  ]);

  return { profile, token };
})();
Jose Paredes
  • 3,882
  • 3
  • 26
  • 50
15

use Promise.all() method:

(async() => {
 let [ profile, token ] = await Promise.all(
  [profileHelper.getUserData(username), 
  tokenHelper.getUserToken(username)
 ])
 return {profile: profile, token: token};
})();

Wait until all ES6 promises complete, even rejected promises

messerbill
  • 5,499
  • 1
  • 27
  • 38
10

You want to use Promise.all

The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

(async() => {
  const response = await Promise.all([
    profileHelper.getUserData(username),
    tokenHelper.getUserToken(username)
  ]);

  return {profile: response[0], token: response[1]};
})();
Michal
  • 4,952
  • 8
  • 30
  • 63
1

The Promise.all method returns a single Promise that resolves when all of the promises in the argument have resolved or when the argument contains no promises.

exports.getServerDetails = async (req, res, next) => {
var getCount = [];
const [ onlineUser, countSchool ] = await Promise.all([
    getOnlineUsers(), // online user count
    getRegisterUser(), // register user
    getRegisterSchools(), // register school count
]);
getCount = [
            {"Online Users": onlineUser},
            {"Registered Users" : countSchool}
        ];
sendJSONresponse(res, 200, {
    status: 'success',
    data: getCount
})
}
async function getOnlineUsers() {
return Login.count({'onlineStatus': 1}, (err, count) => {
    if (err) {
        return err;
    }
    return count;
});
}

async function getRegisterUser() {
return Login.count({}, (err, totResUser) => {
    if (err) {
        return err;
    }
    return totResUser;
})
}

async function getRegisterSchools() {
return Login.count({'role': 'Admin'},(err, totalSchool) => {
    if (err) {
        return err;
    }
    return totalSchool;
})
}