Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ajaxGetter('/api/users', {
'userId': 1234
})
.then( /* do something */ )
.catch( /* Handle Errors */ )
function ajaxGetterExecutor(url, data, resolve, reject) {
$.ajax({
'url': url,
'data': data || undefined,
'type': 'GET',
'success': resolve,
'error': reject
});
}
function ajaxGetter(url, data) {
return new Promise(partial(ajaxGetterExecutor, url, data));
}
function profileDataToArray(data) {
return [data.username, data.email, data.full_name];
}
function displayUsername(data) {
// Using Array.shift allows us to iterate over the data without loops.
$('#username').txt(data.shift());
return data;
}
function displayEmail(data) {
$('#email').txt(data.shift());
return data;
}
function displayFullName(data) {
$('#fullName').txt(data.shift());
// `data` is now an empty array, no need to return
}
getUserProfile(1234)
.then(profileDataToArray)
.then(displayUsername)
.then(displayEmail)
.then(displayFullName)
.catch( /* Handle Errors */ );
function profileDataToArray(data) {
return [data.username, data.email, data.full_name];
}
function display(node, data) {
$(node).txt(data.shift());
return data;
}
getUserProfile(1234)
.then(profileDataToArray)
.then(partial(display, '#username'))
.then(partial(display, '#email'))
.then(partial(display, 'fullName'))
.catch( /* Handle Errors */ );
function getUserProfile(userId) {
return partial(ajaxGetter, '/api/users', {
'userId': userId
});
};
getUserProfile(1234)
.then( /* do something */ )
.catch( /* Handle Errors */ )
function getUserProfileAndDisplay(userId) {
$.ajax({
'url': '/api/users',
'data': {
'userId': userId
},
'type': 'GET',
'success': function(userData) {
$('someNode').txt(userData.username);
$('someOtherNode').txt(userData.email);
},
'error': function() {
// handle error
}
});
}
function partial(fn) {
var args_a = Array.prototype.slice.call(arguments, 1);
return function partialApplicator() {
var args_b = Array.prototype.slice.call(arguments);
return fn.apply(undefined, args_a.concat(args_b));
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment