AngularJS: Waiting for an asynchronous call

前端 未结 3 1534
清歌不尽
清歌不尽 2021-01-04 12:43

I can\'t wrap my head around AngularJS\' concept of promises.

I have a provider:

var packingProvider = angular.module(\'packingProvider\',[]);

packi         


        
3条回答
  •  余生分开走
    2021-01-04 13:13

    There are a ton of resources available that show you how to use Deferreds/Promises with jQuery. Try a search for those and that may help you get over this hurdle. Afaik, the AngularJS promises are the same as the jQuery promises.

    A jQuery promise is used something like this:

    var getPackings = function() { return $.get('../sys/core/fetchPacking.php'); };
    var packings;
    $.when(getPackings()).then(function(data){ packings = data; console.log(packings) });
    

    Keep in mind though that jQuery ajax calls have functions such as .done, .success, etc.. that would replace the generic Deferreds' .when().then() functions.

    In the above jQuery method, you can see that we have to set the data and output it in the .then() function, because you cannot guarantee that the asynchronous process is done anywhere else. So ideally you would call to whatever function continues your processing in the .then() function, like so:

    $.when(myAsyncFunc()).then(myAppCanContinue(dataReturnedByAsyncFunc));
    

    Angular is going to follow the same logic. If you understand the above, it should be easier to understand how to accomplish this in Angular. Also, check out this article that gives simple examples: http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

    In order to get your code to work, you will need to do something like this:

    packingProvider.provider('packingProvider',function(){
        return{
           $get: function($http){
               return{
                  getPackings: function(){
                      return $http.post('../sys/core/fetchPacking.php');
                  }
               }
           }
       }
    });
    var packings = packingProvider.getPackings();
    
    packings.then(function(data) { console.log(data)});
    

提交回复
热议问题