2
function times() {
  var deferred = $q.defer();

  var data = $http.get('https://bus.data.je/latest');

  data.success(function(_data) {
    deferred.resolve(_data);
  });

  data.error(function(error) {
    deferred.reject(error);
  });

  return {
    all: function() {
      return deferred.promise;
    },

    timetable: function(type) {
      _data = deferred.promise;
      return _data.filter(function (el) {
        el = el[0];
        return el.MonitoredVehicleJourney.DirectionRef == type;
      });
    }
  }
}

When either return functions are queried, it returns an object containing promise functions (finally, catch and then), rather than the resolved value. How do I fix this?

2
  • 1
    Avoid the Deferred antipattern! Hint: all references to deferred.promise could simply be replaced by data. Commented Sep 27, 2014 at 19:04
  • 3
    You cannot synchronously get the resolution value of a promise back. Promises are still asynchronous, all you can do is to derive another promise from them. Commented Sep 27, 2014 at 19:05

1 Answer 1

4

You don't. What you do is expose your own API as promise-based:

function times() {
    var deferred = $q.defer();

    var data = $http.get('https://bus.data.je/latest');

    data.success(function(_data) {
        deferred.resolve(_data);
    });

    data.error(function(error) {
        deferred.reject(error);
    });

    return {
        all: function() {
            return deferred.promise;
        },

        timetable: function(type) {
            return deferred.promise.then(function (data) {
                return data.filter(function (el) {
                    el = el[0];
                    return el.MonitoredVehicleJourney.DirectionRef == type;
                });
            });
        }
    }
}

and then use it like so:

times.timetable().then(function (timetables) { /* work with the timetables here */ });

Because, like the comments pointed out, you can't make promises synchronous after the fact.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.