我有这样的服务助手设置:
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
});
最佳答案
首先-您可以简化代码。承诺链是连续性本身的抽象概念。
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();
}
因此-承诺从未实现。
关于javascript - jQuery Deferred无法解决,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24443206/