node.js - Sorting in asynchronous code -


i working on system match volunteers have freeunits (slots of time when free) workunits (slots of times per x number of volunteers required).

the algorithm wish implement sort workunits possible freeunits (workunit.time == freeunit.time) ascending , match them freeunits in order -- want populate workunits hardest fill first.

to accomplish this, workunit model has method possiblefreeunit returns list of freeunit can devoted workunit.

possiblefreeunit: function(next) {    var freeunits = array();   freeunit.find()     .populate("owner")     .where({slot: this.slot})     .exec(function(err, units){        next(units);     }); } 

i use # of possible freeunits in sort function, orders workunits 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 on them in # possiblefreeunits ascending     });    }); 

the problem sort runs after iterate on each of workunits because sort function asynchronous.

what best way overcome this? have tried using settimeout workunits did not appear sorted after delay. wondering if use case promises. lot!

humm. sort async or take function parameter? also, think need bit more information regarding workunit.sort method.

anyhow, high level, can use async module wait completion of async tasks perhaps?


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -