Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

javascript - 无需变量声明即可使用异步迭代(Consume async iterable without variable declaration)

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 。)

This causes StandardJS to give an error on that line, because the variable isn't used.

(这将导致StandardJS在该行上给出错误,因为未使用该变量。)

Is there any way I can iterate over an async generator without having to create a variable?

(有什么方法可以遍历异步生成器而不必创建变量?)

  ask by jens1101 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Current solution(当前解决方案)

Based on the comments to the question and my own research my preferred solution to the problem at the time of writing is the following:

(根据对问题的评论和我自己的研究,在撰写本文时,我对问题的首选解决方案如下:)

 (async () => { async function * asyncGenerator () { yield Promise.resolve(1) yield Promise.resolve(2) yield Promise.resolve(3) console.log('done') } // eslint-disable-next-line no-unused-vars for await (const num of asyncGenerator()) {} })() 

Note the // eslint-disable-next-line no-unused-vars comment which suppresses the warning generated by StandardJS for that one line.

(请注意// eslint-disable-next-line no-unused-vars注释,该注释禁止StandardJS为该行生成的警告。)

Future solution(未来的解决方案)

Once the Iterator Helpers proposal matures and becomes available one could do something like the following for both synchronous and asynchronous generators:

(一旦Iterator Helpers提案成熟并可用,就可以对同步和异步生成器执行以下操作:)

function * syncGenerator () {
  yield 1
  yield 2
  yield 3
  console.log('sync done')
}

syncGenerator().toArray() // Logs 'sync done'

async function * asyncGenerator () {
  yield Promise.resolve(1)
  yield Promise.resolve(2)
  yield Promise.resolve(3)
  console.log('async done')
}

asyncGenerator().toArray() // Logs 'async done'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...