Created
June 29, 2015 05:31
-
-
Save MarshallChen/8e09104839528a63ba7b to your computer and use it in GitHub Desktop.
generator function
This file contains hidden or 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
function asyncDouble(x) { | |
var deferred = Promise.defer(); | |
setTimeout(function() { | |
deferred.resolve(x*2); | |
}, 1000); | |
return deferred.promise; | |
} | |
function consumer(generator){ | |
var cursor = generator(); | |
var value; | |
function loop() { | |
var data = cursor.next(value); | |
if (data.done) { | |
return; | |
} else { | |
data.value.then(function(x) { | |
value = x; | |
loop(); | |
}) | |
} | |
} | |
loop(); | |
} | |
function* myGen() { | |
const data1 = yield asyncDouble(1); | |
console.log("double1: " + data1); | |
const data2 = yield asyncDouble(2); | |
console.log("double2: " + data2); | |
const data3 = yield asyncDouble(3); | |
console.log("double3: " + data3); | |
} | |
consumer(myGen); | |
// double1: 2 | |
// double2: 4 | |
// double3: 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment