0

I have the following code:

//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);

What am I trying to do is to first call a Async function that returns my location. Then in order to get the data from that function I am setting timeout. With the data received I am calling second Async function. And again I am setting timeout in order to get the data from my second Async function, so here it fails. If I try to display the data with console.log() in the timeout block it says undefined while console.log()in the first timeout block works.

I have tried also increasing the timeout time but it just doesn't work. Any suggestions how to get over that ?

radioaktiv
  • 2,437
  • 4
  • 27
  • 36
  • You need to correctly pass callbacks. See http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks Sep 06 '15 at 01:45
  • One of your tags is angularjs so I'd suggest you look into `promise`s http://stackoverflow.com/questions/15604196/promises-in-angularjs-and-where-to-use-them – Jan Sep 06 '15 at 02:02

2 Answers2

0

You could modify your LocalStoresService.getLocalStores method to accept a callback.

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

So your invoking method would look like this:

var coords = LocationService.getLocation();

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

It really depends on the type of technology you're using, as the "correct" implementation of async methods can vary from type to type (AngularJS, NodeJS, vanilla JS etc..)

Davion
  • 881
  • 6
  • 12
0

As i understand your project might be using angularjs i am giving example based on that ,

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

return{

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

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

  }
 });

Now call your API's

LocationService.getLocation().success(function(coords){
       LocationService.getLocalStores(coords).success(function(localStores){
           console.log(localStores);
       });
});
maddygoround
  • 2,145
  • 2
  • 20
  • 32