我一直在尝试使用承诺来实现,通过找到工作时间最短的人来分配人们轮班。为此,我使用aggregate将每个人的可用性文档与包含他们上次工作时间的记录文档链接起来。它似乎跳过了与promises相关的整个代码部分,因为它将selectedPeopleList打印为一个空数组。下面是我的代码:
var selectedPeopleList = [];
var sequentially = function(shifts) {
var p = Promise.resolve();
shifts.forEach(function (){
p=p.then( function() { return collection.aggregate([
{
$lookup:
{
from: "personRecord",
localField: "ATTU_ID",
foreignField: "ATTU_ID",
as: "record"
}
},
{
$match : { 'Available[]' : { $elemMatch : { $eq : shift.value } }, "record.ATTU_ID": { $nin : _.map(selectedPeopleList, 'ATTU_ID') } }
},
{
$sort : { "record.lastShift" : 1 }
}
]).toArray(function(err, docs){
assert.equal(err, null);
}).then(function (result) {
if(docs && docs.length) {
selectedPeopleList.push({ ATTU_ID : docs[0].ATTU_ID, Name: docs[0].Name });
console.log(docs[0]);
}
});
});
})
return p;
};
console.log(selectedPeopleList);发布于 2017-01-24 10:56:42
Promises不会使异步代码同步
将最后一行更改为
p.then(function() {
console.log(selectedPeopleList);
});此外,您不需要在forEach中返回任何内容,因为根本不使用返回值
发布于 2017-01-24 11:02:12
你的代码中有相当多的小错误。
确保你的异步代码流是正确的。我试图解决我的代码片段中的所有问题。
var selectedPeopleList = [];
var sequentially = function(shifts) {
var p = Promise.resolve();
//use promise all to merge all promises in to 1. and use map to return the promises.
Promise.all(shifts.map(function (){
p=p.then( function() { return collection.aggregate([
{
$lookup:
{
from: "personRecord",
localField: "ATTU_ID",
foreignField: "ATTU_ID",
as: "record"
}
},
{
$match : { 'Available[]' : { $elemMatch : { $eq : shift.value } }, "record.ATTU_ID": { $nin : _.map(selectedPeopleList, 'ATTU_ID') } }
},
{
$sort : { "record.lastShift" : 1 }
}
]).toArray(function(err, docs){
assert.equal(err, null);
})
})//make sure you finish then! before you start a new one.
.then(function (result) {
console.log('our results', result);
if(result && result.length) { //use result variable!
selectedPeopleList.push({ ATTU_ID : result[0].ATTU_ID, Name: result[0].Name });
}
});
})
return p;
})
)
.then(function(){ //lets await all the promises first. and then read the list.
console.log(selectedPeopleList);
});
https://stackoverflow.com/questions/41819215
复制相似问题