我正在开发一个系统,以将有FreeUnit的志愿者(免费的时间段)与WorkUnits(需要X个志愿者的次数的时间段)相匹配。以异步代码排序
我希望实现的算法是通过可能的FreeUnits(WorkUnit.time == FreeUnit.time)升序对WorkUnits进行排序,并按顺序将它们与FreeUnits匹配 - 我想填充最难填充的WorkUnits。
为了实现这一点,我的WorkUnit模型有方法possibleFreeUnit,它返回可用于此WorkUnit的FreeUnit列表。
possibleFreeUnit: function(next) {
var freeUnits = Array();
FreeUnit.find()
.populate("owner")
.where({slot: this.slot})
.exec(function(err, units){
next(units);
});
}
我使用可能FreeUnits的#我的排序功能,它通过可能FreeUnits上升的的订单任务包。
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
});
});
问题是在遍历每个工作单元之后运行排序,因为我的排序函数是异步的。
克服这个问题的最好方法是什么?我曾尝试使用setTimeout,但即使延迟后,工作单元也未显示排序。我想知道这是否是一个很好的承诺用例。非常感谢!
是不是你的'.sort('回调信号表明它已完成? – 2014-12-02 02:35:35