0

我无法在此代码中合并每个 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) );

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

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

4

1 回答 1

1

您在收到 .find 的结果之前调用 res.json _prices.find({uname...,因为 .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));
于 2013-06-26T18:38:28.333 回答