立即用AngularJS返回承诺解决 [英] Immediately return a resolved promise using AngularJS
问题描述
我试图让我周围的承诺的头在JavaScript中(尤其是AngularJS)。
I'm trying to get my head around promises in JavaScript (in particular AngularJS).
我有一个服务功能,我们称之为 FooService接口
,如果我们已经加载了一些数据来检查。如果有,我只是希望它回归了,如果我们没有,我们需要加载数据并返回一个承诺:
I have a function in a service, let's call it fooService
, that checks if we've loaded some data. If it has, I just want it to return, and if we haven't, we need to load the data and return a promise:
this.update = function(data_loaded) {
if (data_loaded) return; // We've loaded the data, no need to update
var promise = Restangular.all('someBase').customGet('foo/bar').then(function(data) {
// Do something with the data here
}
return promise;
}
我有另一个函数,然后调用更新
FooService接口
像这样的功能:
fooService.update(data_loaded).then(function() {
// Do something here when update is finished
})
我在这里的问题是,如果我们不需要加载数据在更新
函数,承诺不退还,因此。然后()
不在我的其他函数调用。应该采取什么办法在这里 - 基本上我想从更新立即返回一个解决的承诺()
函数,如果我们不需要从Restangular调用获取数据
My issue here is that if we don't need to load the data in the update
function, a promise isn't returned, so the .then()
is not called in my other function. What should the approach be here - basically I want to return a resolved promise immediately from the update()
function if we do not need to get data from the Restangular call?
推荐答案
目前接受的答案是过于复杂,滥用<一个href=\"http://stackoverflow.com/questions/23803743/what-is-the-deferred-anti-pattern-and-how-do-i-avoid-it\">deferred反面模式的。这里有一个简单的方法:
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
});
};
或者,更进一步:
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;
};
这篇关于立即用AngularJS返回承诺解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!