在 AngularJS 中创建承诺
问题描述:
我正在尝试使用 $q 服务在 Angular 中创建一个承诺.它返回从 Web 服务检索的对象.如果对象在缓存中,它会在不调用 Web 服务的情况下返回它.
I'm trying to create a promise in Angular with the $q service. It returns an object retrieved from a web service. If the object is in the cache, it returns it without calling the web service.
问题是两个解决方案都被调用了.
The problem is that the two resolves are getting called.
也许,我是否使用了 promise 反模式?
Maybe, Am I using a promise anti-pattern?
这是我的代码:
function returnMapAsync() {
return $q(function (resolve, reject) {
if (navigationMap) {
resolve(navigationMap);
} else {
ServerRequest.getNavigationMap().then(function (data) {
navigationMap = data.object;
resolve(navigationMap);
});
}
});
}
谢谢
答
您不需要将所有内容都包含在 $q()
调用中.为了promisify navigationMap
使用 $q.when:
You shouldn't need to wrap everything in the $q()
call. In order to promisify navigationMap
use $q.when:
function returnMapAsync() {
if (navigationMap) {
return $q.when(navigationMap);
}
return ServerRequest.getNavigationMap();
}