Skip to content

Instantly share code, notes, and snippets.

@rosieks rosieks/batch.js
Created Jul 30, 2014

Embed
What would you like to do?
ASP.NET WebApi batching + durandal
define(function () {
var url = '/api/batch',
requests = [],
timeout;
return {
url: url,
get: request('GET'),
post: request('POST'),
delete: request('DELETE'),
put: request('PUT'),
};
function request(type) {
return function (url, data) {
var dfd = $.Deferred();
requests.push({
promise: dfd,
data: {
type: type,
url: url,
data: data
}
});
queueRequest();
return dfd.promise();
};
}
function queueRequest() {
if (!timeout) {
timeout = setTimeout(function() {
var requestsCopy = requests;
requests = [];
console.log('send batch');
// downloaded from https://github.com/volpav/batchjs/blob/master/src/batch.js
$.ajaxBatch({
url: url,
data: $.map(requestsCopy, function (request) { return request.data }),
complete: function (xhr, status, result) {
$.each(result, function (i, result) {
if (result.status >= 400) {
requestsCopy[i].promise.reject(result.data);
}
else {
requestsCopy[i].promise.resolve(result.data);
}
});
}
});
}, 1);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.