Create a promise in AngularJS

I am trying to create a promise in Angular using the $ q service. It returns an object retrieved from the web service. If the object is in the cache, it returns it without calling the web service.

The problem is that two permissions are being called.

Maybe I am using the anti-pattern promise?

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

+3


source to share


2 answers


You don't need to wrap everything in a call $q()

. To promise to navigationMap

use $ q.when :



function returnMapAsync() {

    if (navigationMap) {
        return $q.when(navigationMap);
    }
    return ServerRequest.getNavigationMap();
}

      

+3


source


You don't need to wrap it with another promise as it ServerRequest.getNavigationMap()

is a promise:



function returnMapAsync() {

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

    return ServerRequest.getNavigationMap().then(function(data) {
        navigationMap = data.object;
        return navigationMap;
    });
}

      

+2


source







All Articles