Skip to content

Instantly share code, notes, and snippets.

@fengdi
Created June 5, 2014 18:31
Show Gist options
  • Save fengdi/c0abcee8e4f5332e74ea to your computer and use it in GitHub Desktop.
Save fengdi/c0abcee8e4f5332e74ea to your computer and use it in GitHub Desktop.
// An example of using yield to simplify the callback hell.
// The limitation is, this only apply to whose callbacks take the normal form of function(err, result), more arguments are ignored.
// Maybe there are many workarounds, but keep it simple, the ECMAScript 6 is around the corner.
function Async(task) {
var gen = task(callback);
function callback(err, result) {
if(err) {
throw err;
}
else {
gen.next(result);
}
};
gen.next();
};
Async(function*(callback) {
console.log(0);
yield setTimeout(callback, 1000);
console.log(1000);
yield setTimeout(callback, 1000);
console.log(2000);
yield setTimeout(callback, 1000);
console.log(3000);
return;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment