我试图编写一个返回承诺的函数。但有些时候,请求的信息可以立即获得。我想用一个承诺来包装它,这样消费者就不需要做决定了。
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?