递归查找函数调用然后合并结果

时间:2013-06-26 16:49:45

标签: javascript node.js mongodb mongoose

我无法在此代码中合并每个FIND函数的结果:

this.result = [];
    _products.find().exec(function (err,products) {
        this.products = products;
        var productsCollection = [];
        for(i=0;i<products.length;i++) {
            _prices.find({uname:products[i].uname},function(err,prices){

                var resultItem = {product:products[i],prices:prices}
                this.result.push(resultItem)
            }.bind(this))

        }
            res.json(200, this.result);
    }.bind(this) );

没有错误......但响应是一个空数组:(

请帮助...我如何合并结果?

1 个答案:

答案 0 :(得分:1)

在收到_prices.find({uname...的结果之前,你正在调用res.json,因为.find是异步的。简单的解决方案是使用async循环遍历数组并在收到所有结果时调用res.json。

var async = require('async');
this.result = [];

_products.find().exec(function (err, products) {
    // async.map takes an array and constructs a new array from it
    // async.each and this.result.push() would also work but I find .map to be cleaner
    async.map(products, function (product, next) {
        _prices.find({ uname: product.uname }, function(err, prices){
            // By passing the object to next here it will be passed to the
            // final callback below
            next(err, { product: product, prices: prices });
        });
    }, function (err, result) {
        // This callback will nicely wait until all queries above has finished
        this.result = result;
        res.json(200, result);
    });
}.bind(this));