【问题标题】:Issue while getting array value in NodeJS在 NodeJS 中获取数组值时出现问题
【发布时间】:2013-04-19 12:09:17
【问题描述】:

我正在使用 NodeJS 来计算不同部门的员工人数。我使用 Mongoose 作为 ODM 和 MongoDB 作为数据库。这是我的代码(非常简单的测试目的)。

   exports.list= function( req, res){
    var array = ['sectionA', 'sectionB'];
    var i;
    for(i = 0; i<array.length; i++){
        Issue.count({ 'section.name': array[i]}, function (err, count) {
          console.log('Section name is: ' + array[i] + ' number of employees: ' + count );
        )};
     }
    }

但是array[i] 的值在Issue.count({ 'section.name': array[i]}, function (err, count) {}); 内部是未定义的。但是count的值是绝对正确的。我想要这样的输出:

Section name is: sectionA number of employees: 50
Section name is: sectionB number of employees: 100

但我目前的输出是

 Section name is: undefined number of employees: 50
 Section name is: undefined number of employees: 100

这是因为iIssue.count({ 'section.name': array[i]}, function (err, count) {}); 中的值始终为2。

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

    Issue.count 函数有可能是异步的吗?所以你的循环在回调之前完成:

    function (err, count) {
      console.log('Section name is: ' + array[i] + ' number of employees: ' + count );
    }
    

    被执行。执行回调时,结果 i 的值未定义。

    【讨论】:

      【解决方案2】:

      @eshortie 是正确的:Issue.count 是异步的,这就是问题所在。

      这里有一个解决方案:

      for (i = 0; i<array.length; i++) {
        Issue.count({ 'section.name': array[i]}, function(sectionName, err, count) {
          console.log('Section name is: ' + sectionName + ' number of employees: ' + count );
        }.bind(null, array[i]));
      }
      

      【讨论】:

        【解决方案3】:

        不要尝试使用常规的for 循环来执行异步函数。它在问问题。使用async.eachSeriesasync.each 代替https://github.com/caolan/async#eachseriesarr-iterator-callback

        var async = require('async')
        var Issue = {} // mongoose isue model here
        var elements = ['foo', 'bar']
        async.eachSeries(
          elements,
          function(name, cb) {
            var query = {
              'section.name': name
            } 
            Issue.count(query, function(err, count) {
              if (err) { return cb(err) }
              console.dir(name, count)
            })
          },
          function(err) {
            if (err) {
              console.dir(err)
            }
            console.log('done getting all counts')
          }
        )
        

        【讨论】:

          【解决方案4】:

          使用 Q 库

            var Q = require('q')
              var i = 0;
          
              function hello (item){
          
                 var defer = Q.defer();
          
                  Issue.count({'section.name': student}, function (err, count) {
                         if(err){
          
                           defer.reject(err);
          
                          }else{
          
                           var result = 'Section name is: ' + item + ' number of employees: ' + count ;
                           defer.resolve(result)
          
                           }
          
                      });
          
              })
                     return defer.promise;
                }
          
          
                function recall(){
                  hello(checkItems[i]).then((val)=>{
                    console.log(val)
                    if(i < checkItems.length - 1){
                      i++
                      recall();
                    }
                  })
                }
              recall()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-08-23
            • 2019-11-18
            • 1970-01-01
            • 1970-01-01
            • 2019-09-04
            相关资源
            最近更新 更多