Reputation: 20179
I have a service helper setup like this:
var service = {
getSettings: function () {
var that = this,
deferred = $.Deferred();
that.getThingOne().done(function (data) {
that.getThingTwo(data.Element).done(function (data) {
deferred.resolve(data);
});
});
return deferred.promise();
},
getThingTwo: function (elm) {
return $.getJSON('http://ajax-call-here');
},
getThingOne: function () {
var deferred = $.Deferred();
navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject, {
enableHighAccuracy: true
});
return deferred.promise();
}
};
When I call into it doing something like this I never reach below. What is going on?
service.getSettings().done(function(data) {
// never reach here
});
Upvotes: 0
Views: 516
Reputation: 276596
First - You can simplify your code quite a bit. Promises chain and are an abstraction on the notion of continuation itself.
getSettings: function () {
var that = this; // this line can be avoided as well
return this.getThingOne().then(function (data) {
// returning from a `.then` will cause the promise to resolve with that
// return value
return that.getThingTwo(data.Element);
});
}
Second, your promisification doesn't work. Try to preserve the context:
getThingOne: function () {
var deferred = $.Deferred();
navigator.geolocation.getCurrentPosition(
function(v){ deferred.resolve(v); }, // preserve context
function(e){ deferred.reject(e;) }, { // here too
enableHighAccuracy: true
});
return deferred.promise();
}
Because of this - the promise never got resolved.
Upvotes: 2