简体   繁体   English

在while循环内使用await是否是个坏习惯

[英]Is it a bad practice to use await inside a while loop

Is it a bad practice to use a await inside a while loop? 在while循环内使用await是一种不好的做法吗?

I have the following code: 我有以下代码:

// 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)
}

I have a couple of questions here: 我在这里有几个问题:

  1. Is it ok to use two res variables? 可以使用两个res变量吗?
  2. Am I going to use performance because I'm using a await inside a while loop? 我是否会因为在while循环中使用await而使用性能?
  3. Is there a better solutin? 有没有更好的溶质?

Thank you in advance. 先感谢您。

Is it ok to use two res variables? 可以使用两个res变量吗?

No. The way you are using the inner one, the access in the arguments is always in the temporal dead zone and you will always get an exception. 否。您使用内部方式的方式是,参数中的访问始终在时间盲区中,并且始终会出现异常。

Am I going to use performance because I'm using a await inside a while loop? 我是否会因为在while循环中使用await而使用性能?

There's nothing wrong with using await in loops, as long as you expect them to run sequentially and not all iterations concurrently. 只要在循环中使用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)
}

Notice also that if errorHandler comes from a callback parameter, you should drop the entire try / catch and just use .catch(errorHandler) on the promise returned by the call. 还要注意,如果errorHandler来自回调参数,则应删除整个try / catch ,仅对调用返回的promise使用.catch(errorHandler)

Also, while I don't know what api.resource.show does, it looks like you are polling for a result. 另外,虽然我不知道api.resource.show作用,但看起来您正在轮询结果。 It would be better if the method would just return a promise that fulfills at the right time. 如果该方法仅返回在正确时间实现的承诺,那将更好。 If that is not possible and you need to poll, I would recommend at least some delay between the calls. 如果那是不可能的,并且您需要轮询,我建议两次通话之间至少要有一些延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM