Create promise in AngularJS

谁说胖子不能爱 提交于 2019-12-20 02:28:27

问题


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


回答1:


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



回答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;
    });
}


来源:https://stackoverflow.com/questions/31024021/create-promise-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!