gpt4 book ai didi

javascript - JavaScript 中双向生成器的实际使用

转载 作者:可可西里 更新时间:2023-11-01 02:08:54 26 4
gpt4 key购买 nike

来自 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 }

最佳答案

大卫沃尔什有一个 blog about 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 }

但同样,用例与您的示例一样制造。

他在总结中说

It's natural to wonder what this new exotic toy is going to do practically for your code. There's a lot more to them, though. We've just scratched the surface. So we have to dive deeper before we can discover just how powerful they can/will be.

  • How does error handling work?
  • Can one generator call another generator?
  • How does async coding work with generators?

Those questions, and more, will be covered in subsequent articles here, so stay tuned!

In a later blog他有以下片段(和其他一些片段)

// 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 );
} );

这似乎更真实一些。

他总结

Put simply: a generator + yielded promise(s) combines the best of both worlds to get really powerful and elegant sync(-looking) async flow control expression capabilities. With simple wrapper utilities (which many libraries are already providing), we can automatically run our generators to completion, including sane and sync(-looking) error handling!

关于javascript - JavaScript 中双向生成器的实际使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34503535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com