I'm now developing on a jQuery plugin, and I want to make some pre-process operations before $.ajax
sends:
// The signature is the same with $.ajax
$.myAjax = function(url, options) {
var data = options.data;
var promises = [];
for(var name in data) {
if(data.hasOwnProerty(name)) {
var val = data[name];
if(val instanceof File) {
// I want to do some async pre-process here.
var dfd = $.Deferred();
var reader = new FileReader();
reader.onload = function(e) {
data.name = e.target.result;
dfd.resolve();
}
reader.readAsText(val);
promises.push(dfd.promise());
}
}
}
var deferred = $.Deferred();
$.when.apply($, promises).done(function() {
// In fact, I want to return, or wrap cascading this jqXHR
// in the outer function `$.myAjax`.
var jqXHR = $.ajax(url, options).done(function(...) {
// ??? If I want deferred to be a jqXHR like object,
// how to wrap the arguments here?
deferred.resolve(/* Help to fill */);
}).fail(function(...) {
deferred.reject(/* Help to fill */);
});
});
// ** ATTENTION **
// Here, I want to return a jqXHR compatible promise.
// That is what I ask here.
return deferred.promise();
}
And I want to return a Deferred object in myAjax
, or more precisely speaking, a jqXHR object.
So that I can call, completely the same interface with a standard $.ajax
method:
$.fn.myAjax({...}).done(function(data, textStatus, jqXHR) {
// ...
}).fail(function(jqXHR, textStatus, errorThrown) {
// ...
})
// .always ... etc.