我使用的是nodejs+express+mongoose。假设我有 2 个架构和模型:“水果”和“蔬菜”。
假设我有以下内容:
var testlist = ["Tomato", "Carrot", "Orange"];
var convertedList = [];
// Assume res is the "response" object in express
我希望能够分别对照“水果”和“蔬菜”集合检查数组中的每个项目,并将它们插入到转换后的列表中,其中番茄、胡萝卜和西兰花被替换为各自的文档。
下面我有一些我认为的伪代码,但不知道如何做到这一点。
for(var i = 0; i < testlist.length; i++) {
var fruitfind = Fruit.find({"name":testlist[i]});
var vegfind = Vegetables.find({"name":testlist[i]});
// If fruit only
if(fruitfind) {
convertedList.push(fruitfindresults);
}
// If vegetable only
else if(vegfind) {
convertedList.push(vegfindresults);
}
// If identified as a fruit and a vegetable (assume tomato is a doc listed under both fruit and vegetable collections)
else if (fruitfind && vegfind) {
convertedList.push(vegfindresults);
}
}
// Converted List should now contain the appropriate docs found.
res.send(convertedList) // Always appears to return empty array... how to deal with waiting for all the callbacks to finish for the fruitfind and vegfinds?
最好的方法是什么?或者这可能吗?
最佳答案
假设每种水果/蔬菜只有一种,并且您打算将在两个集合中都找到的蔬菜推送两次。
var async = require("async"),
testlist = ["Tomato", "Carrot", "Orange"];
async.map(testlist, function (plant, next) {
async.parallel([function (done) {
Fruit.findOne({"name": plant}, done);
},
function (done) {
Vegetables.findOne({"name": plant}, done);
}], function (err, plants) { // Edited: before it was (err, fruit, veggie) which is wrong
next(err, plants);
});
},
function (err, result) {
var convertedList = [].concat(result);
res.send(convertedList);
});
注意:尚未实际测试代码,但它应该可以工作。 The async module顺便说一句,非常适合管理这样的回调。
更新
要只获取每个水果一次,只需像这样重写 async.parallel 回调:
function (err, plants) {
next(err, plants[0] || plants[1]);
}
.map 回调中不再需要 concat:
function (err, result) {
res.send(result);
}
关于node.js - 如何同步请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16401354/