【发布时间】:2015-10-28 18:31:59
【问题描述】:
注意:我使用的是 jQuery 版本 1.7.2。
我正在尝试理解 jQuery 承诺和延迟对象。
我有以下代码:
var that = this;
var dataRetrieved = that.retrieveData();
$.when(dataRetrieved).then(function(data) {
that.formatDataForTemplate(data);
});
retrieveData: function () {
if ( // condition A ) {
return window.data.conditionA;
} else if (// condition B) {
return window.data.conditionB;
} else {
this.fetch({
success: function (status, response) {
return response;
}
});
}
}
基本上,我想将从retrieveData 返回的任何数据传递给.then() 函数,但它似乎不起作用。正在调用 retrieveData() 函数(使用 console.log 检查),但未调用 formatDataForTemplate。
retrieveData() 可能会立即返回数据,也可能会从 AJAX 查询 (this.fetch({});) 返回数据。我需要 .then() 仅在从 retrieveData 返回数据后触发。
我想我只是没有清楚地理解承诺。如何让我的代码完成我想要做的事情?
编辑:嗯,还没有完全掌握它的窍门。这是我的更新版本。我试图弄清楚如何返回已用我的数据解决的承诺。
var that = this;
var dataRetrieved = that.retrieveData();
dataRetrieved.then(function(data) {
that.formatDataForTemplate(data, that.get('template'));
});
retrieveData: function () {
var that = this;
if (window.settings.preview === 'true') {
return $.Deferred(function(def) {
def.resolveWith(window.settings.previewData);
});
}
// else if mock (during dev), use mock data.
else if (this.get('is_mock')) {
var mocked_data = {
"title":"Mock Title",
"description": "Mock Description"
};
// return mocked_data;
return $.Deferred(function(def) {
def.resolveWith(mocked_data);
});
}
// else, hit API like normal.
else {
return $.Deferred(function (def) {
that.fetch({
success: function (status, response) {
def.resolveWith(response);
}
});
});
}
},
【问题讨论】:
-
retrieveData当然需要返回一个与 $.when 一起使用的承诺,否则 $.when 将无法判断它应该何时完成。 -
@KevinB - 对不起,我很笨,你能详细说明一下吗?如何在
retrieveData中同时返回我需要的数据和一个承诺? -
您将返回一个承诺,该承诺稍后将使用您需要的数据来解决。
-
你能发布一个例子来说明你的意思吗?我很难想象。
标签: jquery ajax backbone.js jquery-deferred .when