2016-03-12 24 views
0

我使用SailsJS創建了一個應用程序。我有一個關於在異步瀑布和異步中使用回調的問題。SailsJS異步瀑布函數中的嵌套回調函數沒有返回正確的值

我有一個異步瀑布函數中的兩個函數。第一個回調返回正確的值。第二個函數有一個嵌套的回調函數。但是,嵌套回調的值會卡在水線查找函數中,並且永遠不會返回到外部函數。

你知道我該如何將值返回給外部函數嗎?

感謝您的幫助。

myFunction: function (req,res) { 
async.waterfall([ 
    function(callback){ 
     // native MongoDB search function that returns an Array of Objects 
    }, 
    function(result, callback){ 
     async.each(resultAll, function (location){ 
      Model.find({location:'56d1653a34de610115d48aea'}).populate('location') 
      .exec(function(err, item, cb){ 
       console.log (item) // returns the correct value, but the value cant be passed to the outer function 
      }) 
     }) 
     callback(null, result); 
    }], function (err, result) { 
     // result is 'd' 
     res.send (result) 
    } 
)} 

回答

0

當您使用異步的功能,你應該,你應該用你的回調,一旦你與你想執行操作完成。 例如:

async.waterfall([ 
    function(cb1){ 
     model1.find().exec(function(err,rows1){ 
      if(!err){ 
       model2.find({}).exec(function(err,rows2){ 
        var arr=[rows1,rows2]; 
        cb1(null,arr); 
       }); 
      }else 
       cb1(err); 
     }) 
    },function(arr,cb2){ 
    /** 
    * here in the array....we will find the array of rows1 and rows2 i.e.[rows1,rows2] 
    * */ 
     model3.find().exec(err,rows3){ 
      if(!err){ 
       arr.push(rows3); 
      // this arr will now be [rows1,rows2,rows3] 
      } 
      else 
       cb2(err); 
     } 
     cb1(null,arr); 
    }], 
    function(err,finalArray){ 
     if(err){ 
     // error handling 
     } 
     else{ 
     /** 
     * in finalArray we have [rows1,rows2] ,rows3 is not there in final array 
     * beacause cb2() was callbacked asynchronously with model3.find().exec() in second function 
     */ 
     } 
    }); 

所以根據我的代碼應該像

async.waterfall([ 
     function(callback){ 
      // native MongoDB search function that returns an Array of Objects 
     }, 
     function(result, callback){ 
      async.each(resultAll, function (location){ 
       Model.find({location:'56d1653a34de610115d48aea'}).populate('location') 
        .exec(function(err, item, cb){ 
         console.log (item) // returns the correct value, but the value cant be passed to the outer function 
         callback(null, yourData); 
         /** 
         * yourData is the data whatever you want to recieve in final callbacks's second parameter 
         * i.e. callback(null,item) or callback(null,[result,item]) or callback(null,result) 
         */ 
        }) 
      }) 
     }], function (err, result) { 
     // result is 'd' 
     res.send (result) 
    } 
); 

應用這一點,你可以看到在最終的回調,你想要的東西。

+0

嗨,謝謝你。現在,該值已通過,但未定義。你知道這可能是爲什麼嗎? – steph

+0

你得給我看看那個代碼! 我使用像我解釋的異步,這就是每個人都這樣做。重新審視和調試你的代碼,否則發送給我的消息。 – vkstack

+0

您是否將回調(null,yourData)更改爲回調(null,item)? – vkstack