2016-03-12 26 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