Skip to content

Instantly share code, notes, and snippets.

@kishmiryan-karlen
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kishmiryan-karlen/bd6ae8df50a236606dd8 to your computer and use it in GitHub Desktop.
Save kishmiryan-karlen/bd6ae8df50a236606dd8 to your computer and use it in GitHub Desktop.
// jQuery AJAX simulator
var $ = {
ajax: function(opts, returnData, throwError) {
console.log(`Request URL: ${opts.url}`);
console.log(`Request data: ${opts.data}`);
var timer = Math.round() * 10 + 1;
if (throwError && typeof opts.error === 'function') {
setTimeout(function() {
opts.error({
message: 'AJAX Request Error!'
});
}, timer);
return;
}
if (typeof opts.success === 'function') {
setTimeout(function() {
opts.success(returnData);
}, timer);
}
}
};
// Simple wrapper for $.ajax() call
function request(opts, returnData, throwError) {
opts.success = function(result) {
it.next(result);
};
opts.error = function(err) {
it.throw(err.message);
};
$.ajax(opts, returnData, throwError);
}
// The generator method, which starts the requests
function* main() {
var res =
yield request({
url: 'http://example.com/auth'
}, {
id: 24
});
var user =
yield request({
url: 'http://example.com/profile',
data: res.id
}, {
name: 'Karlen'
});
console.log('User info: ' + JSON.stringify(user));
}
// Running the generator and starting the first iteration
var it = main();
it.next();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment