当前位置: 代码迷 >> JavaScript >> 节点异步控制流
  详细解决方案

节点异步控制流

热度:40   发布时间:2023-06-13 11:36:51.0

我正在尝试使用节点中的twitter数据,并且遇到了一些我认为应该与节点样式编码有关的障碍。 代码块用于获取推文,检查文本是否在mongo中,以及是否未插入。

我发现的第一个绊脚石是,尝试将i打印到控制台时,它将始终对每个i进行迭代,然后再开始对光标进行迭代。 我认为,如果我能澄清一下,这可能会帮助我前进。 这是足够的信息来帮助我吗?

我所拥有的是:

T.get('statuses/user_timeline', options , function(err, data) {

     var db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
        if(err)
            throw err;
        console.log("connected to the mongoDB !");
        myCollection = db.collection('test_collection2');

        for (var i = 0; i < data.length ; i++) {
            //let's wrap this in a loop
            docu = data[i];
            //console.dir(data);
           console.dir(i);
           var cursor = myCollection.find({text : data[i].text}).limit(1);
           cursor.each(function(err, doc) {
              if (doc != null) {
                    console.dir('doc is not null');
                    console.dir(doc.text);
              } else {
                    console.dir('doc is null - inserting');
                    myCollection.insert(docu, function(err, records){
                       console.log("Record added as "+records.text);
                       });
              }
           })
        }
    });
})

问题仅仅是因为Javascript是异步的。 在Mongo中的find函数为您提供返回值之前,循环已完成。

我将进行以下或类似的操作-只是为了解释这个概念:

T.get('statuses/user_timeline', options , function(err, data) {

 var db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err)
        throw err;
    console.log("connected to the mongoDB !");
    myCollection = db.collection('test_collection2');

    var myfunction = function(correct_i,docu){
      var cursor = myCollection.find({text : data[correct_i].text}).limit(1);
       cursor.each(function(err, doc) {
          if (doc != null) {
                console.dir('doc is not null');
                console.dir(doc.text);
          } else {
                console.dir('doc is null - inserting');
                myCollection.insert(docu, function(err, records){
                   console.log("Record added as "+records.text);
                   });
          }
       })
    };

    for (var i = 0; i < data.length ; i++) {
        //let's wrap this in a loop
        docu = data[i];
        //console.dir(data);
       console.dir(i);
       myfunction(i,docu);

    }
    });
})

这样,每次对Mongo的查找/查找都将具有正确的i。 因为该函数将其作为参数获取

  相关解决方案