I am working on a system to match Volunteers who have FreeUnits (slots of time when they are free) to WorkUnits (slots of times per which X number of volunteers are required).
The algorithm I wish to implement is sort WorkUnits by possible FreeUnits (WorkUnit.time == FreeUnit.time) ascending and match them to FreeUnits in that order -- I want to populate the WorkUnits that are hardest to fill first.
To accomplish this, my WorkUnit model has method possibleFreeUnit that returns a list of FreeUnit that can be devoted to this WorkUnit.
possibleFreeUnit: function(next) {
var freeUnits = Array();
FreeUnit.find()
.populate("owner")
.where({slot: this.slot})
.exec(function(err, units){
next(units);
});
}
I use the # of possible FreeUnits in my sort function, which orders WorkUnits by number of possible FreeUnits ascending.
WorkUnit.find()
.populate("owner")
.then(function(workunits) {
sails.log("before sort");
workunits.sort(function(a, b){
a.possibleFreeUnit(function (aFreeUnits){
b.possibleFreeUnit(function (bFreeUnits){
sails.log(a.toString() + ": " + aFreeUnits.length +
" vs " + b.toString() + ": " + bFreeUnits.length);
return aFreeUnits.length - bFreeUnits.length;
});
});
});
workunits.forEach(function(workunit){
sails.log(workunit.toString());
//this code should iterate over them in # possibleFreeUnits ascending
});
});
The problem is that the sort runs after I iterate over each of the workunits because my sort function is asynchronous.
What is the best way to overcome this? I have tried using setTimeout but workunits did not appear sorted even after a delay. I am wondering if this is a good use case for promises. Thanks a lot!