创建AngularJS承诺AngularJS

2023-09-13 05:21:32 作者:太萌怪我咯

我试图创造角的承诺与$ Q服务。它返回从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.

也许,我使用一个承诺反模式?

Maybe, Am I using a promise anti-pattern?

下面是我的code:

    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();
}