javascript - 在 while 循环中使用 wait 是一个坏习惯吗

标签 javascript node.js loops asynchronous async-await

在 while 循环中使用 wait 是一个不好的做法吗?

我有以下代码:

// this is inside a async function
try {
  let res = await api.resource.create(...args) // create resource
  do {
    let res = await api.resource.show(res.body.id)
    if (res.body.status === 'COMPLETED')
      return res.body
  } while(1)
} catch (err) {
  errorHandler(err)
}

我有几个问题:

  1. 可以使用两个 res 变量吗?
  2. 我会因为在 while 循环内使用await 而使用性能吗?
  3. 有更好的解决方案吗?

提前谢谢您。

最佳答案

Is it ok to use two res variables?

没有。您使用内部的方式,参数中的访问始终位于 temporal dead zone 中。并且你总会遇到异常(exception)。

Am I going to use performance because I'm using a await inside a while loop?

在循环中使用 await 没有任何问题,只要您希望它们按顺序运行而不是所有迭代同时运行即可。

Is there a better solution?

try {
  let res = await api.resource.create(...args) // create resource
  do {
    res = await api.resource.show(res.body.id)
  } while (res.body.status !== 'COMPLETED')
  return res.body
} catch (err) {
  errorHandler(err)
}

另请注意,如果 errorHandler 来自回调参数,则应删除整个 try/catch 并仅在调用返回的 Promise 上使用 .catch(errorHandler)

此外,虽然我不知道 api.resource.show 的作用,但看起来您正在轮询结果。如果该方法只返回一个在正确时间履行的 promise ,那就更好了。如果这是不可能的并且您需要轮询,我建议在调用之间至少有一些延迟。

关于javascript - 在 while 循环中使用 wait 是一个坏习惯吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50252789/

相关文章:

arrays - 有没有办法在用户输入特定数字之前创建数组?

php - 如何停止循环并添加值?

ios - iPhone 上的 HTTP 实时流媒体服务器

javascript - 空 Node.js/Express 响应

具有意外 cpu 消耗的 C 多线程进程

javascript - Apps 脚本自定义函数 - 内部错误

node.js - docker/nodejs/mongodb部署:MongooseError [MongooseServerSelectionError]:连接超时

javascript - 根据对象属性禁用按钮

javascript - 使用 Node Express js 下载文件

javascript - 为什么它在保存的文件中添加反斜杠?