简体   繁体   中英

How to write an asynchronous method returning a promise in angularjs?

I'm developing an AngularJS application.

I try to write a service method that can periodically auto reload some content from HTTP request and notify the controller that called the method.

So I search to use the promse API of AngularJS and I use the $timeout service, but I can't return the promise while the method is running not asynchronously...

So here, the promise is never returned, and I understand why, but I don't know what is the correct pattern to do what I want.

angular.module('myModule')

.factory('myService', [
    '$timeout',
    '$q',
    '$doMyHttpRequest',
function($timeout, $q, $doMyHttpRequest){

    var d = $q.defer();

    return function(){        
        autoRefresh = function(){

            $timeout(function(){
                $doMyHttpRequest(function(){
                    d.notify({ // notify the update success
                        updated: true
                    });
                },function(){
                    d.notify({ // notify the update error
                        updated: false
                    });             
                });
                this.autoRefresh(); // refresh again in 60 seconds
            },60000);

        };
        this.autoRefresh();  

        return d.promise;
    }

}])

.controller('myCtrl', ['myService', function(myService){

    myService().autoRefresh().then(function(){ // never reached because promise is never returned
        // do my stuff when succeed
    },function(){ // never reached because promise is never returned
        // do my stuff when error
    });

}])

;

please see here : http://jsbin.com/wiveli/1/edit

app.controller('firstCtrl', function($timeout,  doMyHttpRequest){

        function onSucess() {

              console.log("sucess");
               autoRefresh();

            };
         function onError() {

              console.log("error");
              autoRefresh();

            }


    function autoRefresh(){




        $timeout(function(){
         doMyHttpRequest.getData().then(onSucess, onError);

        },1000);  

    }
   autoRefresh();

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM