【问题标题】:Is it possible to wrap a setInterval in an async generator function?是否可以将 setInterval 包装在异步生成器函数中?
【发布时间】:2020-06-22 17:24:00
【问题描述】:

不使用Streams API,是否可以在异步生成器函数中包装setInterval,以模拟永无止境的流?

我知道如何使用setTimeout 来提供延迟。

使用setTimeout

const wait = (delay = 500) => new Promise((resolve) => setTimeout(resolve, delay))

async function * countUp(count = 0) {           
    while(1) (await wait(), yield count++)           
}

(async ()=> {
    for await(let el of countUp())
        console.log(el)
})()

【问题讨论】:

  • 你试过什么(TM)
  • 我目前看不到方法,所以我什么也没尝试。
  • 你可以,但我认为它不会像使用 setTimeout 作为承诺延迟那样整洁。
  • @52d6c6af 很公平,我想你的问题是规则的例外。

标签: javascript


【解决方案1】:

。或者:不容易。异步生成器函数是基于 Promise 的,Promise 不能很好地处理重复的回调。另外setInterval 不支持任何形式的背压。

当然,您可以自己实现流 API,这归结为制作a queue of promises。您可以从该答案中获取代码并编写

function countUp(count = 0) {
    const q = new AsyncBlockingQueue()
    setInterval(() => {
        q.enqueue(count++)
    }, 500)
    return q // has a Symbol.asyncIterator method
}

(async() => {
    for await (const el of countUp())
        console.log(el)
})()

【讨论】:

  • 所以答案实际上是“是”,但要困难得多?
  • 如果消费者跟不上生产速度,不仅更困难,而且效率更低,甚至可能不正确
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-14
  • 2015-02-13
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多