jquery ajax.then,jquery - 如何将骨干函数的结果传递到jQuery $ .when()。then()? - 堆栈内存溢出...

注意:我正在使用jQuery 1.7.2版。

我正在尝试了解jQuery Promise和延迟对象。

我有以下代码:

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 。

this.fetch({}); 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);

}

});

});

}

},