来自C#世界,我很想知道javascript中双向生成器的一些实际用法.我可以理解生成器在一般情况下是如何有用的,但在涉及双向生成器时则不然.我们可以将它与RxJS一起使用或喜欢吗?你能解释一下可以使用它的任何模式/场景吗?
function* interrogate() {
let name = yield "What is your name?";
let color = yield "What is your favorite color?";
return `${name}'s favorite color is ${color}.`;
}
let it = interrogate();
it.next(); // { value: "What is your name?", done: false }
it.next('Ethan'); // { value: "What is your favorite color?", done: false }
it.next('orange'); // { value: "Ethan's favorite color is orange.", done:true }
Run Code Online (Sandbox Code Playgroud)
David Walsh有一个关于ES6 Generators的博客
他有一个例子
function *foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var it = foo( 5 );
// note: not sending anything into `next()` here
console.log( it.next() ); // { value:6, done:false }
console.log( it.next( 12 ) ); // { value:8, done:false }
console.log( it.next( 13 ) ); // { value:42, done:true }
Run Code Online (Sandbox Code Playgroud)
但同样,用例就像你的例子一样制造.
在他的总结中,他说
很自然地想知道这个新奇特的玩具会为你的代码做些什么.不过,他们还有更多.我们刚刚触及表面.因此,在我们发现它们能够/将会有多强大之前,我们必须深入研究.
- 错误处理如何工作?
- 一台发电机能调用另一台发电机
- 异步编码如何与生成器一起工作?
这些问题以及更多内容将在后续文章中介绍,敬请期待!
在稍后的博客中,他有以下片段(以及其他一些片段)
// run (async) a generator to completion
// Note: simplified approach: no error handling here
function runGenerator(g) {
var it = g(), ret;
// asynchronously iterate over generator
(function iterate(val){
ret = it.next( val );
if (!ret.done) {
// poor man's "is it a promise?" test
if ("then" in ret.value) {
// wait on the promise
ret.value.then( iterate );
}
// immediate value: just send right back in
else {
// avoid synchronous recursion
setTimeout( function(){
iterate( ret.value );
}, 0 );
}
}
})();
}
runGenerator( function *main(){
var result1 = yield request( "http://some.url.1" );
var data = JSON.parse( result1 );
var result2 = yield request( "http://some.url.2?id=" + data.id );
var resp = JSON.parse( result2 );
console.log( "The value you asked for: " + resp.value );
} );
Run Code Online (Sandbox Code Playgroud)
这似乎更真实的世界.
他总结道
简单地说:生成器+产生的promise(s)结合了两个世界的优点,以获得真正强大而优雅的同步( - 查看)异步流控制表达能力.使用简单的包装器实用程序(许多库已经提供),我们可以自动运行我们的生成器,包括理智和同步(查看)错误处理!