Created
June 5, 2014 18:31
-
-
Save fengdi/c0abcee8e4f5332e74ea 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
// 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