Wait For All Different Promise To Finish Nodejs (async Await)
I am currently waiting for all the promise to finish sequentially like this: (async() => { let profile = await profileHelper.getUserData(username); let token = await tokenH
Solution 1:
(async() => {
const [ profile, token ] = await Promise.all([
profileHelper.getUserData(username),
tokenHelper.getUserToken(username)
]);
return { profile, token };
})();
Solution 2:
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
Solution 3:
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]};
})();
Solution 4:
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 ] = awaitPromise.all([
getOnlineUsers(), // online user countgetRegisterUser(), // register usergetRegisterSchools(), // register school count
]);
getCount = [
{"Online Users": onlineUser},
{"Registered Users" : countSchool}
];
sendJSONresponse(res, 200, {
status: 'success',
data: getCount
})
}
asyncfunctiongetOnlineUsers() {
returnLogin.count({'onlineStatus': 1}, (err, count) => {
if (err) {
return err;
}
return count;
});
}
asyncfunctiongetRegisterUser() {
returnLogin.count({}, (err, totResUser) => {
if (err) {
return err;
}
return totResUser;
})
}
asyncfunctiongetRegisterSchools() {
returnLogin.count({'role': 'Admin'},(err, totalSchool) => {
if (err) {
return err;
}
return totalSchool;
})
}
Post a Comment for "Wait For All Different Promise To Finish Nodejs (async Await)"