问题描述
我正在尝试编写一个返回承诺的函数.但有时请求的信息可以立即获得.我想把它包装在一个承诺中,这样消费者就不需要做出决定.
I am trying to write a function that returns a promise. But there are times when the information requested is available immediately. I want to wrap it in a promise so that the consumer doesn't need to make a decision.
function getSomething(id) {
if (Cache[id]) {
var deferred = $q.defer();
deferred.resolve(Cache[id]); // <-- Can I do this?
return deferred.promise;
} else {
return $http.get('/someUrl', {id:id});
}
}
像这样使用它:
somethingService.getSomething(5).then(function(thing) {
alert(thing);
});
问题是回调不会为预先解析的承诺执行.这是合法的事情吗?有没有更好的方法来处理这种情况?
The problem is that the callback does not execute for the pre-resolved promise. Is this a legitimate thing to do? Is there a better way to handle this situation?
推荐答案
简短回答:是的,您可以在返回之前解析 AngularJS 承诺,它会按照您的预期运行.
Short answer: Yes, you can resolve an AngularJS promise before you return it, and it will behave as you'd expect.
来自 JB Nizet 的 Plunkr 但重构为在最初要求的上下文中工作(即函数调用服务)并实际在现场.
From JB Nizet's Plunkr but refactored to work within the context of what was originally asked (i.e. a function call to service) and actually on site.
服务内部...
function getSomething(id) {
// There will always be a promise so always declare it.
var deferred = $q.defer();
if (Cache[id]) {
// Resolve the deferred $q object before returning the promise
deferred.resolve(Cache[id]);
return deferred.promise;
}
// else- not in cache
$http.get('/someUrl', {id:id}).success(function(data){
// Store your data or what ever....
// Then resolve
deferred.resolve(data);
}).error(function(data, status, headers, config) {
deferred.reject("Error: request returned status " + status);
});
return deferred.promise;
}
控制器内部....
somethingService.getSomething(5).then(
function(thing) { // On success
alert(thing);
},
function(message) { // On failure
alert(message);
}
);
希望对大家有所帮助.我没有发现其他答案很清楚.
I hope it helps someone. I didn't find the other answers very clear.
这篇关于你能在返回之前解决一个 angularjs 承诺吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!