sam*_*ner 25 javascript promise angularjs restangular angular-promise
我试图了解JavaScript中的承诺(特别是AngularJS).
我在服务中有一个函数,让我们调用它fooService,检查我们是否加载了一些数据.如果有,我只想让它返回,如果我们没有,我们需要加载数据并返回一个承诺:
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;
}
Run Code Online (Sandbox Code Playgroud)
我有另一个函数然后调用这样的update函数fooService:
fooService.update(data_loaded).then(function() {
// Do something here when update is finished
})
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我们不需要在update函数中加载数据,则不返回promise,因此.then()不会在我的其他函数中调用.该方法应该在这里 - 基本上我想立即从update()函数返回一个已解决的承诺,如果我们不需要从Restangular调用中获取数据?
Elo*_*Elo 43
由于您的承诺使用与JavaScript本机相同的语法,您可以使用并返回已经解析的JavaScript承诺:Promise.resolve()
return(Promise.resolve("MyReturnValue"));
Run Code Online (Sandbox Code Playgroud)
Ben*_*aum 27
当前接受的答案过于复杂,并且滥用延迟的反模式.这是一个更简单的方法:
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
});
};
Run Code Online (Sandbox Code Playgroud)
或者,甚至更进一步:
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;
};
Run Code Online (Sandbox Code Playgroud)
AngularJS的$ q服务将在这里为您提供帮助.这很像Kris Kowal的Q promise图书馆.
当您有一个可以返回promise或值的异步方法时,请使用$ q.when方法.它将传递给它,无论是承诺还是价值,并根据传递的承诺创建将被解决/拒绝的承诺,或者如果传递值,则解决.
$q.when( fooService.update(data_loaded) ).then(function(data){
//data will either be the data returned or the data
//passed through from the promise
})
Run Code Online (Sandbox Code Playgroud)
然后在您的更新函数中返回数据而不是仅返回
if (data_loaded) return data_loaded;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24365 次 |
| 最近记录: |