在 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)
}
我有几个问题:
- 可以使用两个 res 变量吗?
- 我会因为在 while 循环内使用await 而使用性能吗?
- 有更好的解决方案吗?
提前谢谢您。
最佳答案
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/