2

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?

Here is my code:

    function returnMapAsync() {

  return $q(function (resolve, reject) {
    if (navigationMap) {
      resolve(navigationMap);
    } else {
      ServerRequest.getNavigationMap().then(function (data) {
        navigationMap = data.object;
        resolve(navigationMap);
      });
    }
  });
}

Thank you

RPallas
  • 557
  • 7
  • 22
  • 2
    [Yes you are](http://stackoverflow.com/q/23803743/1048572) - good that you've asked :-) – Bergi Jun 24 '15 at 10:29
  • see also [How to return an object in my case?](http://stackoverflow.com/q/28057294/1048572) – Bergi Jun 24 '15 at 10:34

2 Answers2

3

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();
}
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
2

You don't need to wrap it into one more promise since ServerRequest.getNavigationMap() is a promise:

function returnMapAsync() {

    if (navigationMap) {
        return $q.resolve(navigationMap);
    } 

    return ServerRequest.getNavigationMap().then(function(data) {
        navigationMap = data.object;
        return navigationMap;
    });
}
dfsq
  • 191,768
  • 25
  • 236
  • 258