【问题标题】:recursive find function calls then merge result递归查找函数调用然后合并结果
【发布时间】:2013-06-27 02:38:28
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案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));
    

    【讨论】:

    • 谢谢你 verry musch ...我是 php 开发人员 ...不知道异步:D
    猜你喜欢
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2019-07-23
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多