Wait for all different promise to finish nodejs (a

2019-04-07 10:06发布

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.

4条回答
倾城 Initia
2楼-- · 2019-04-07 10:14
(async() => {
  const [ profile, token ] = await Promise.all([
    profileHelper.getUserData(username),
    tokenHelper.getUserToken(username)
  ]);

  return { profile, token };
})();
查看更多
何必那么认真
3楼-- · 2019-04-07 10:18

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]};
})();
查看更多
女痞
4楼-- · 2019-04-07 10:33

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

查看更多
成全新的幸福
5楼-- · 2019-04-07 10:38

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;
})
}
查看更多
登录 后发表回答