0

I am running into an issue where the client is not waiting for the server response. I have a big query that runs on server and returns data. But on client side, it is not waiting for the response from server before processing the data. I tried angularjs .then function without success. Service is "myService" as below.

this.getJsonData = function() {
    var searchData =  caller.get("/metadata/Search").then(function(result){
      return result.data;
    });
    return searchData;
  };

calling service

myService.getJsonData().then(
    function(data) {
     formatData(data);
    },
    function(err) {
      console.log("Error here" + err);
    });

Now formatData is called, while the response from server call in pending in getJsonData.

Can anyone please help me what could be done here to resolve the issue.

**********Edited********** Tried this but didn't work either

this.getJsonData = function() {
    var deffered = $q.seDefer();
    caller.get("/metadata/Search").then(function(result){
      deffered.resolve(result.data);
    });
    return deffered.promises;
  };
user2406718
  • 263
  • 4
  • 15
  • Could this data be loaded upfront before loading DOM content? – mdlars Sep 08 '15 at 20:59
  • i can only run this data fetch when user clicks on a button – user2406718 Sep 08 '15 at 21:01
  • And you are trying to do so via an ajax request? If so then you may want to add a loading modal to the page to show users that work is happening in the background, then just hide the modal when the data is available from the outgoing ajax request. – mdlars Sep 08 '15 at 21:03
  • its not an UI screen blocker issue. Even before the data is returned, formatData loop is getting executed resulting in error. It has to do something with $q, defer and resolve functions in promises. – user2406718 Sep 08 '15 at 21:06
  • Yes, promises would definitely be the route that you want to go. See this for an example: http://stackoverflow.com/questions/27238928/angularjs-http-call-in-a-service-return-resolved-data-not-promises – mdlars Sep 08 '15 at 21:08

1 Answers1

0

Here is an example of how you can use promises with long running calls: http://fiddle.jshell.net/82vLx76y/

By returning a promise from a function, we can defer the execution of another chained function and make use of the first functions return value. See Angular's $q service documentation for more info: https://docs.angularjs.org/api/ng/service/$q

mdlars
  • 909
  • 10
  • 16