convert some async loops into parallel loops

If you use `await` inside a loop it makes the loop inherently serial.

If you omit the `await` however, the tasks will all start but the loop
will finish while the tasks are still being scheduled.

So, to make a set of tasks run in parallel but then have the
code block after the loop once all the tasks have been completed
you have to get an array of Promises (one for each iteration) and
then use `Promise.all()` to wait for those promises to be resolved.
Using `Array#map` is a convenient way to go from an array of inputs
to the require array of Promises.
This commit is contained in:
Ray Bellis 2019-02-01 00:07:06 +00:00
parent 07ae44ddf4
commit e7c2fad7b0
2 changed files with 51 additions and 48 deletions

View file

@ -43,20 +43,19 @@ exports.deleteGroup = async function(groupID)
throw new customError("groupID does not exist", "apierror");
}
// iterate through all pads of this group and delete them
for (let padID in group.pads) {
let pad = await padManager.getPad(padID);
await pad.remove();
}
// iterate through all pads of this group and delete them (in parallel)
await Promise.all(Object.keys(group.pads).map(padID => {
return padManager.getPad(padID).then(pad => pad.remove());
}));
// iterate through group2sessions and delete all sessions
let group2sessions = await db.get("group2sessions:" + groupID);
let sessions = group2sessions ? group2sessions.sessionsIDs : [];
let sessions = group2sessions ? group2sessions.sessionsIDs : {};
// loop through all sessions and delete them
for (let session in sessions) {
await sessionManager.deleteSession(session);
}
// loop through all sessions and delete them (in parallel)
await Promise.all(Object.keys(sessions).map(session => {
return sessionManager.deleteSession(session);
}));
// remove group and group2sessions entry
await db.remove("group2sessions:" + groupID);