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

Javascript 递归查找函数调用,然后合并结果,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我无法在此代码中合并每个查找函数的结果: 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].

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

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) );
this.result=[];
_products.find().exec(函数(err,products){
这一点。产品=产品;
var productsCollection=[];

对于(i=0;i您在收到prices.find({uname…
)的结果之前调用res.json,因为.find是异步的。简单的解决方案是在数组中循环,并在收到所有结果时调用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));

谢谢你,我是一名php开发人员…我不知道异步:D