2016-04-27 3 views
0

Imがなぜわからない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 
    }); 
    } 

だから、私がJobsアレイ内のそれらのジョブをプッシュしたにもかかわらず、res.json(Jobs)で最後にJobs配列を送信しようとすると、空のジョブがあることに気がついたら。

答えて

1

コードの問題は、JobResults.forEachが同期で、forEachループ内で非同期JobOffer.findを呼び出すことです。したがって、プログラムは非同期操作が完了してすぐに次の(エラー、ジョブ)を呼び出すのを待つことはありません。代わりにfor each async.eachを使用し、async.eachが終了したときにのみnext(err、Jobs)を呼び出します。私はまた、あなたがエラーがある場合でもnullを渡しているここでは、たとえば、あなたはすべてのコールバックでERR値をチェックしていることを確認するために助言する:

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

はそれが役に立てば幸い、あなたが他が必要な場合は私に知らせてあなたのコードを助けてください。

関連する問題