0

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!

kmangutov
  • 3
  • 2

1 Answers1

0

Humm. Is your sort truly async or does it just take a function as a parameter? Also, I think we will need a bit more information regarding the workunit.sort method.

Anyhow, as a high level, you can use something like async module to wait for the completion of async tasks perhaps?

lwang135
  • 576
  • 1
  • 3
  • 13