SocketIO/Mongoose JS .push to 数组问题

SocketIO/Mongoose JS .push to array issue

这是使用 NodeJS、SocketIO 和 Mongoose。

客户端按钮正在触发服务器端 'LoadF' 套接字,它应该通过 mongoose 进行 3 次查询并在套接字回调中发回结果。我正在尝试将每个 Mongoose 查询结果推送到一个数组,该数组将作为单个字符串化 JSON 发回。

问题是 .push 没有填充 'doc' 数组。我认为这可能是范围问题,但我已经尝试了所有我能想到的组合,但没有结果。

代码(仅显示所需的 3 个猫鼬查询中的一个):

socket.on('loadF', function(data,callback){
        var doc = [];
        console.log("before:" + toString(doc));
        filldoc(function(err, assets){
            if (err) return console.error(err);
            console.log("during:" + assets);
            doc.push(JSON.stringify(assets));
        });
        callback(doc.join(','));
        console.log("after:" + doc[0]);
        function filldoc(callback){
            initCm.find({}, function(err, assets){
                if (err) return callback(err, null);
                callback(null, assets[0]);
            });
        }
    });

这是我从日志中得到的没有错误的输出:

before:[object Undefined]
after:undefined
during:{ _id: 54e4c934b61b8b6824ff38aa,
  id: 'document',
  version: '1.0',
  __v: 0 }

'during' 输出显示应该放入数组的内容。

但不确定为什么 'during' 在 'after' 之后?无论我尝试什么,情况似乎总是如此。

filldoc() 是异步的。这意味着您只能处理它在您提供的回调中创建的结果。这些代码行的当前位置:

callback(doc.join(','));
console.log("after:" + doc[0]);

将 运行 在 filldoc 完成其工作并调用其回调之前,因此 doc 仍然是空的。相反,您需要像这样在回调中移动它们:

socket.on('loadF', function(data,callback){
    var doc = [];
    console.log("before:" + toString(doc));
    filldoc(function(err, assets){
        if (err) return console.error(err);
        console.log("during:" + assets);
        doc.push(JSON.stringify(assets));
        callback(doc.join(','));
        console.log("after:" + doc[0]);
    });

    function filldoc(callback){
        initCm.find({}, function(err, assets){
            if (err) return callback(err, null);
            callback(null, assets[0]);
        });
    }
});