Immediately return a resolved promise using AngularJS

后端 未结 5 1098
故里飘歌
故里飘歌 2020-12-10 00:57

I\'m trying to get my head around promises in JavaScript (in particular AngularJS).

I have a function in a service, let\'s call it fooService, that chec

5条回答
  •  攒了一身酷
    2020-12-10 01:30

    The current accepted answer is overly complicated, and abuses the deferred anti pattern. Here is a simpler approach:

    this.update = function(data_loaded) {
        if (data_loaded) return $q.when(data);  // We've loaded the data, no need to update
    
        return Restangular.all('someBase').customGet('foo/bar')
                                 .then(function(data) {
            // Do something with the data here 
        });
    };
    

    Or, even further:

    this._updatep = null;
    this.update = function(data_loaded) { // cached
        this._updatep = this._updatep || Restangular.all('someBase') // process in
                                                    .customGet('foo/bar'); //.then(..
        return this._updatep;
    };
    

提交回复
热议问题