在node.js中的循环范围之后,我无法获得值

时间:2014-07-29 11:56:01

标签: node.js

我无法在node.js中的循环范围之后得到值

for (var i = 0; i < project_list[0].KeywordsId.length; i++) {
    keywordModel.find({
        _id: project_list[0].KeywordsId[i]
    }, function(err, keywords) {
        keywordsArray.push(keywords[0].text);
    });
}
console.log(">>>>>>>>>>>>>>>>>>>>>>", keywordsArray);

1 个答案:

答案 0 :(得分:0)

您必须编写异步代码才能执行此操作。在你的情况下,它将是这样的

https://github.com/caolan/async#map

var async = require('async'),
  keywords;

async.map(project_list[0].KeywordsId, 
   function(id, cb){
    keywordModel.find({ _id: id }, cb);
}, function(error, keywordsFound){
  if(error){
    throw error; 
  } else {
    keywords = keywordsFound;
  }
});


setTimeout(function(){
//we have to wait for keywords to be found  
console.log(keywords);
}, 1000);