在地图中使用瀑布 node.js
Using waterfall in map node.js
async.map(map, function(item, mnext){
async.waterfall([
function(wnext){
console.log("1");
//mongodb queryies something like
db.collection.find().toArray(function(err){
if(err){
wnext(err);
}else{
wnext();
}
})
},
function(wnext){
console.log("2");
//mongodb queryies something like
db.collection.find().toArray(function(err){
if(err){
wnext(err);
}else{
wnext();
}
})
},
function(wnext){
console.log("3");
//mongodb queryies something like
db.collection.find().toArray(function(err){
if(err){
wnext(err);
}else{
wnext();
}
})
}
], function(err){
if(err){
mnext(err);
}else{
mnext();
}
})
})
根据地图的计数,我预计会看到 1 2 3 1 2 3 1 2 3
。但情况并不如我所料。我意识到它打印为 1 2 1 2 3 3
或 1 2 3
以外的其他内容。我不明白怎么会这样。因为它是瀑布而且结构是真实的我猜?那么我们可以说地图或瀑布有问题吗?或者它 async.map 是异步的所以它覆盖了瀑布?
我不知道..而且我被困住了。我错过了什么?? 1 2 3
不是预期的顺序吗?
如果您看到 async.map
文档 https://caolan.github.io/async/docs.html#map,
Note, that since this function applies the iteratee to each item in
parallel, there is no guarantee that the iteratee functions will
complete in order
是的。 async.map
是平行的。要实现你想要的,请使用 async.mapSeries
https://caolan.github.io/async/docs.html#mapSeries
async.map(map, function(item, mnext){
async.waterfall([
function(wnext){
console.log("1");
//mongodb queryies something like
db.collection.find().toArray(function(err){
if(err){
wnext(err);
}else{
wnext();
}
})
},
function(wnext){
console.log("2");
//mongodb queryies something like
db.collection.find().toArray(function(err){
if(err){
wnext(err);
}else{
wnext();
}
})
},
function(wnext){
console.log("3");
//mongodb queryies something like
db.collection.find().toArray(function(err){
if(err){
wnext(err);
}else{
wnext();
}
})
}
], function(err){
if(err){
mnext(err);
}else{
mnext();
}
})
})
根据地图的计数,我预计会看到 1 2 3 1 2 3 1 2 3
。但情况并不如我所料。我意识到它打印为 1 2 1 2 3 3
或 1 2 3
以外的其他内容。我不明白怎么会这样。因为它是瀑布而且结构是真实的我猜?那么我们可以说地图或瀑布有问题吗?或者它 async.map 是异步的所以它覆盖了瀑布?
我不知道..而且我被困住了。我错过了什么?? 1 2 3
不是预期的顺序吗?
如果您看到 async.map
文档 https://caolan.github.io/async/docs.html#map,
Note, that since this function applies the iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order
是的。 async.map
是平行的。要实现你想要的,请使用 async.mapSeries
https://caolan.github.io/async/docs.html#mapSeries