With a synchronous JavaScript generator I can iterate over it as follows:
(使用同步JavaScript生成器,我可以对其进行如下迭代:)
(() => { function * syncGenerator () { yield 1 yield 2 yield 3 console.log('done') } Array.from(syncGenerator()) })()
This will simply iterate over the whole generator without having to initialise a variable.
(这将简单地遍历整个生成器,而无需初始化变量。)
I would like to do the same with async generators.(我想对异步生成器做同样的事情。)
The closest solution I could come up with is as follows:(我能想到的最接近的解决方案如下:)
(async () => { async function * asyncGenerator () { yield Promise.resolve(1) yield Promise.resolve(2) yield Promise.resolve(3) console.log('done') } for await (const num of asyncGenerator()) {} })()
Unfortunately I had to instantiate the variable num
in the above code snippet.
(不幸的是,我不得不在上面的代码片段中实例化变量num
。)
(这将导致StandardJS在该行上给出错误,因为未使用该变量。)
Is there any way I can iterate over an async generator without having to create a variable?(有什么方法可以遍历异步生成器而不必创建变量?)
ask by jens1101 translate from so