【问题标题】:Use Asynchronous Iteration to do polling in my backend使用异步迭代在我的后端进行轮询
【发布时间】:2018-11-13 00:39:21
【问题描述】:

使用异步迭代来显示后端中某些资源的状态是一种好习惯吗?例如:

const item = driver.get(idOfDriver)

try {
  for await (const { status } of item) {
    console.log(status)
  }
} catch (err) {
  // do something here
} finally {
  // the driver arrived in the final location
  const { finalLocation, id } = item
  console.log(`final location of driver ${id} is ${finalLocation`)
}

我正在做一些异步迭代不适合的事情?

提前致谢。

【问题讨论】:

  • 那么item 是一个发出状态更新的无限迭代器?那么finally 有什么用呢?
  • @Bergi 不是无限的...当驱动程序到达该位置时,将存在新的属性(finalLocation 就是一个例子)。迭代器将存在以发出状态,直到状态!= 'COMPLETE'
  • 除非您需要发出那些不完整的状态,否则我看不出迭代器有什么用处。只需对新属性使用一个简单的承诺
  • @Bergi 我需要在界面中显示当前状态

标签: javascript promise eventemitter


【解决方案1】:

如果我弄错了,请纠正我,但我猜你只是尝试在get 中启动数据获取并等待它加载,然后进行一些处理。在这种情况下,您不需要在处理一系列 Promise 时在更复杂的场景中使用的异步迭代。

您可以使用 ES6 承诺来做到这一点:

driver.get(idOfDriver)
  .then(({ finalLocation, id }) => {
    console.log(`final location of driver ${id} is ${finalLocation`)
  })
  .catch(err => console.error(err))

或者使用 ES7 async/await 语法:

try {
  const {finalLocation, id} = await driver.get(idOfDriver);
  console.log(`final location of driver ${id} is ${finalLocation`)
}
catch(err) {
  console.error(err)
}

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 2018-10-09
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    相关资源
    最近更新 更多