node.js - 在 Node 中返回 JSON 数组

标签 node.js asynchronous express

我仍在尝试了解 Node.js 中的异步流程。我正在尝试读取 db 中的文件列表并将结果转换为 json 数组并返回。该代码适用于一个 json 对象。但读取完整数组时没有输出

这就是代码

函数调用 - 接收来自浏览器的ajax请求并返回结果

module.retrieveSourceContent(req, res, result, function(err, result){
                if(err){
                  console.log(err);
                  return;
                }
                console.log(result);
                res.contentType('json');
                res.write(JSON.stringify(result));
                res.end();
            });

代码

 retrieveSourceContent : function(req, res, sourceList, callback){
        var sourceContent = new Array();
        MongoClient.connect(config.mongoPath+config.dbName, function(err, db) {
           if(err){
             return callback(new Error("Unable to Connect to DB"));
           }
           var collection = db.collection(config.source);
           for( i=0;i<sourceList['sources_FOR'].length;i++){
              //build the source JSON Array
              collection.find({'_id':sourceList['sources_FOR'][i]}).nextObject(function(err, doc) {
                if(err)
                  return callback(new Error("Error finding data in DB"));
                    var sourceObject = {
                        title     :doc.name,
                        tagCount  :doc.tag.length,
                        tags      :doc.tag,       
                        format    :doc.type,     // Differentiate text, image, video and urls
                        content   :doc.data      // Content
                    };
                    sourceContent.push(sourceObject);
                    //if(i == sourceList['sources_FOR'].length - 1)
                      return callback(null, sourceContent);

              });
           }
        });
      }

此代码向客户端返回一个 json 对象。如果我取消注释 if(i == sourceList['sources_FOR'].length - 1) 我没有输出,也没有错误。但是 sourceContent.push(sourceObject); 确实成功创建了 json 数组。

由于该流程适用于其他语言,我怀疑它与 Node 的异步流程有关。我不知道如何解决这个问题。

任何帮助都会很棒..

最佳答案

由于格式的原因,遵循程序流程有点困难。但我认为你假设这与异步行为有关是正确的。如果我没有被格式所迷惑,在我看来,您在循环的每次迭代中都进行了回调,这仅适用于第一次迭代。我不确定您的 sourcesList 是什么,但我会尝试构建一个包含 sourcesList 中所有项目的查询。那么你就不需要 for 循环了。也许你可以使用$in运算符。

关于node.js - 在 Node 中返回 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15877577/

相关文章:

angularjs - npm 无法安装 angular-cli

node.js - 如何更新 ember 包?

xml2js 不解析通过代理检索的 xml

javascript - 忽略旧的多个异步 ajax 请求

javascript - URL 重写在 Express 4.14.1 中不起作用

node.js - 用 mongoose 对 alpha 进行排序

node.js - 如何在 Node.js 中正确打开和维护与多个 Mongo 数据库的连接?

c# - 嵌套 Async Await 不等待

c# - 即使我的服务器套接字已收到所有字节,为什么 SendAsync 不会在 SocketAsyncEventArgs 上引发 Completed 事件?

node.js - 提供多种内容类型