异步功能将数据传递给异步功能

问题描述:

我有以下代码:异步功能将数据传递给异步功能

//calling AsyncFunction 
var coords = LocationSerivice.getLocation(); 
var localStores; 

setTimeout(function(){ 

      //works 
      console.log(coords); 

      //calling async function again 
      localStores = LocalStoresService.getLocalStores(coords[0],coords[1]); 



     }, 100); 

     setTimeout(function(){ 

        //doesn't work 
        console.log(localStores); 



       }, 100); 

什么是我想要做的是首先调用一个异步函数,返回我的位置。然后为了从该功能获取数据,我正在设置超时。随着收到的数据,我打电话给第二个异步功能。我再次设置超时为了从我的第二个异步函数获取数据,所以在这里失败。如果我尝试在超时块中显示console.log()的数据,则表示undefined,而第一个超时块​​中的console.log()工作。

我也尝试过增加超时时间,但它不起作用。 任何建议如何克服?

+0

您需要正确传递回调。见http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks

+0

你的标签之一是angularjs,所以我建议你看看'promise's http://*.com/问题/ 15604196/promises-in-angularjs-and-where-use-them – Jan

您可以修改您的LocalStoresService.getLocalStores方法以接受回调。

function getLocalStores (arg1, arg2, cb) { 
    // do stuff. 
    var localStores = 'w/e'; 
    if (typeof cb === 'function') return cb(localStores); 
} 

所以你的调用方法是这样的:

var coords = LocationService.getLocation(); 

LocalStoresService.getLocalStores(coords[0], coords[1], function (localStores) { 
    console.log(localStores); // 'w/e' 
}); 

这真的取决于你所使用的技术类型,如“正确”的实现异步方法可以改变从类型式(angularJS,的NodeJS,香草JS等)

+2

其中一个问题的标记是angularjs,所以我认为承诺是要走的路 – Jan

+0

我完全同意,Angular是在Ionic的核心,所以这里没有争论。我给了香草JS的一个例子,因为在我看来,他在初学者水平。 – Davion

+0

太棒了!承诺解决了我的问题:) – radioaktiv

据我了解你的项目可能会使用angularjs我给例如此基础上,

.factory('LocationSerivice', function ($http) { 

return{ 

    getLocation : function() { 
     return $http.get('location_api'); 
    }; 

    getLocalStores : function(coords){ 
     return $http.get('your_local_store_api'); 
    }; 

    } 
}); 

现在致电您的API

LocationService.getLocation().success(function(coords){ 
     LocationService.getLocalStores(coords).success(function(localStores){ 
      console.log(localStores); 
     }); 
});