使用 AngularJS 立即返回已解决的承诺 [英] Immediately return a resolved promise using AngularJS
问题描述
我正在尝试了解 JavaScript(特别是 AngularJS)中的 promise.
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
的 update
函数,如下所示:
I have another function that then calls the update
function of fooService
like so:
fooService.update(data_loaded).then(function() {
// Do something here when update is finished
})
我的问题是,如果我们不需要在 update
函数中加载数据,则不会返回承诺,因此 .then()
在我的其他函数中没有调用.这里应该采用什么方法 - 基本上,如果我们不需要从 Retangular 调用中获取数据,我想立即从 update()
函数返回一个已解决的承诺?
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?
推荐答案
目前接受的答案过于复杂,滥用了延迟反模式.这是一个更简单的方法:
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屋!