我有这样的服务助手设置:
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();
}
};
当我打电话给它做这样的事情时,我从未到达下面。发生了什么事?
service.getSettings().done(function(data) {
// never reach here
});
答案 0 :(得分:2)
首先 - 你可以简化你的代码。承诺链是对延续本身概念的抽象。
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);
});
}
其次,你的承诺不起作用。尝试保留上下文:
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();
}
因此 - 承诺永远不会得到解决。