Last active
August 29, 2015 14:22
-
-
Save kishmiryan-karlen/bd6ae8df50a236606dd8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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