2016-04-27 33 views
0

即時得到一個空數組在Async.waterfall不知道爲什麼月底在貓鼬的元素添加到陣列中的嵌套查詢,但這樣我的代碼看起來怎麼樣:我試着使用Node.js的

exports.GetJobs = function(req,res){ 
    var Jobs =[]; ///// Jobs is a global variable 

    async.waterfall([ 
     function(next){ 
      // get my alert 
      UserAlertDB.find({User:req.user.id},function(err,AlertResult){ 
       next(null,AlertResult); 
      }) 
     }, 
     function(AlertResult, next) { 

      // You might get an error if you do not have created an alert so AlertResult[0].Words will not exist 
      if(AlertResult) // if Alert Result not equal to null then query by alert 
      { 
       JobDB.find({title: new RegExp(AlertResult[0].Words, 'i')}, function (err, JobResults) { 

        if (err) console.log(err); 
        // If the job matches the requirements for alert then push it to the list 
        JobResults.forEach(function(job){ 
         JobOffer.find({JobID : job._id, JobOfferOwnerID: req.user.id}, function(err,Offers){ 
          if(err) console.log("Error Inside Querying Jobs Result for Alert " + err); 

          if(Offers.length==0){ 
           console.log("Jobs are : " + JSON.stringify(Jobs)) // when I print the Jobs array here it shows that a job is getting pushed into the array 
           Jobs.push(job); 
          } 
         }) 

        }) 
        next(err,Jobs) // But Jobs here is empty 
       }) 
      } 
      else{ 
       next("There is an error",null) 
      } 
     } 
    ], function(err,Jobs){ 
     console.log(JSON.stringify(Jobs)); ////// Getting Empty Jobs here 
     if(err) console.log("Error Inside Get Jobs Match Alert Data in Server : " + err); 
     res.json(Jobs); ////// Jobs here is empty 
    }); 
    } 

所以如果你注意到當我試圖用res.json發送Jobs數組時(Jobs)有空作業,儘管我已經將這些作業推到了Jobs數組中。

回答

1

你的代碼中的問題是JobResults.forEach是同步的,你在forEach循環中調用異步JobOffer.find。因此,您的程序不會等待異步操作完成並立即調用下一個(err,Jobs)。只有在async.each完成後,forEach纔會使用async.each並調用next(err,Jobs)。我也建議,以確保你正在檢查在每一個回調的ERR的值,例如現在你在這裏傳遞null即使有可能是錯誤:

// get my alert 
UserAlertDB.find({User:req.user.id},function(err, AlertResult) { 
    next(err, AlertResult); 
}) 

希望它能幫助,讓我知道如果你需要任何其他幫助你的代碼。