I have the following example JS code:
function loadData(url, data) {
return $.get(url, data ? data : {});
}
function example1() {
showSpinner();
$.when(loadData('/example1', { hello: 'world' }))
.then(function (resp) {
// do something with the data
})
.always(function(){
hideSpinner();
})
.fail(function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR);
});
}
function example2() {
showSpinner();
$.when(loadData('/example2', { hello: 'world' }))
.then(function (resp) {
// do something with the data
})
.then(function () {
// do something else
})
.always(function(){
hideSpinner();
})
.fail(function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR);
});
}
Both example1() and example2() use the same promise logic and will do something different with the returned data and then always hide the spinner and handle the failures the same (if any). The issue is that I may want to do different things after the data is loaded in each example and have multiple then's follow.
However I am having to repeat the always and fail code. How can I make them more DRY so they are only written once but used in both scenarios (and other examples if need be). So I can't just move the when into a method and pass a callback as there maybe more than one and in different then`s. So this wouldn't work:
function customPromise(load, callback) {
showSpinner();
$.when(load)
.then(function (resp) {
callback(resp);
})
.always(function(){
hideSpinner();
})
.fail(function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR);
});
}
function example3() {
customPromise(loadData('/example2', { hello: 'world' }));
}