Created
July 23, 2016 16:41
-
-
Save ekoneko/3839a13d4fab595597cc6810099191ad to your computer and use it in GitHub Desktop.
async generator
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
/** | |
* 一个异步生成器的简单函数实现 | |
* 演示参照下方exec | |
*/ | |
var async = function (makeGenerator) { | |
return function () { | |
var generator = makeGenerator(); | |
var continuer = function (result, value) { | |
if (result && result.done) { | |
return; | |
} | |
result = generator.next(value); | |
if (result.value instanceof Promise) { | |
result.value.then((value)=> { | |
continuer(result, value); | |
}); | |
} else { | |
continuer(result); | |
} | |
} | |
continuer(); | |
} | |
} | |
/* DEMO */ | |
var aPromsieFunction = function () { | |
return new Promise( (resolve, reject) => { | |
setTimeout(function(){ resolve('resolve1');}, 1000); | |
}); | |
} | |
var anotherPromiseFunction = function () { | |
return new Promise( (resolve, reject) => { | |
setTimeout(function(){ resolve('resolve2');}, 1000); | |
}); | |
} | |
var exec = async(function* () { | |
var r1 = yield aPromsieFunction(); | |
console.log('r1', r1); | |
var r2 = yield anotherPromiseFunction(); | |
console.log('r2', r2); | |
}); | |
exec(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment