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/f8cb1a61cd27ebe038cb to your computer and use it in GitHub Desktop.
Save kishmiryan-karlen/f8cb1a61cd27ebe038cb to your computer and use it in GitHub Desktop.
Using AJAX with generators. Demonstrating the exception throwing and handling as well as caching the data.
// 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);
}
}
};
var cache = {};
// Simple wrapper for $.ajax() call
function request(opts, returnData, throwError) {
if (cache[opts.url]) {
setTimeout(function() {
it.next(cache[opts.url]);
});
} else {
opts.success = function(result) {
cache[opts.url] = result;
it.next(result);
};
opts.error = function(err) {
it.throw('Error: ' + 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
});
try {
var user =
yield request({
url: 'http://example.com/profile',
data: res.id
}, {
name: 'Karlen'
}, true);
console.log('User info: ' + JSON.stringify(user));
} catch (ex) {
console.log('Error: ' + ex);
}
}
// 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