我有以下代码:
//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()有效。
我也试过增加超时时间,但就是不起作用。有什么建议可以帮你克服这个问题吗?
发布于 2015-09-06 09:54:44
您可以修改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、vanilla JS等)。
发布于 2015-09-06 11:33:28
据我所知,您的项目可能会使用angularjs,我在此基础上给出了示例。
.factory('LocationSerivice', function ($http) {
return{
getLocation : function () {
return $http.get('location_api');
};
getLocalStores : function(coords){
return $http.get('your_local_store_api');
};
}
});LocationService.getLocation().success(function(coords){
LocationService.getLocalStores(coords).success(function(localStores){
console.log(localStores);
});
});https://stackoverflow.com/questions/32419249
复制相似问题