Skip to content

Instantly share code, notes, and snippets.

@MarshallChen
Created June 29, 2015 05:31
Show Gist options
  • Save MarshallChen/8e09104839528a63ba7b to your computer and use it in GitHub Desktop.
Save MarshallChen/8e09104839528a63ba7b to your computer and use it in GitHub Desktop.
generator function
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