[英]How to avoid await inside a loop
I have the following code:我有以下代码:
const data = res?.advancedResult?.data;
for (const referential of data) {
const entities = await EntityDAO.find({ query: { referential: referential?._id } });
for (const entity of entities) {
const items = await ItemDAO.find({ query: { entity: entity?._id } });
entity.items = items.length;
}
referential.entities = entities.map(entity => ({ name: entity.name, items: entity.items }));
}
Since I'm using eslint I got the following error:由于我使用的是 eslint,因此出现以下错误:
[eslint] Unexpected `await` inside a loop. (no-await-in-loop)
I can't use Promise.all
since the iterations of a loop are not actually independent of each-other.我不能使用
Promise.all
因为循环的迭代实际上并不相互独立。
Is there anyway to avoid the await insid the loop so i can boost the performance?有没有办法避免循环内部的等待,这样我就可以提高性能? or i just should silence the error by adding
/* eslint-disable no-await-in-loop */
或者我应该通过添加
/* eslint-disable no-await-in-loop */
错误
It seems that you are suffering from the classic "N+1 Selects" problem.看来您正遭受经典的“N+1 选择”问题。 There are several ways to go about it - the last one being preferable:
有几种方法可以 go 关于它 - 最后一种更可取:
p-limit
).p-limit
类的模块)。WHERE entity IN (value1, value2, ...)
.WHERE entity IN (value1, value2, ...)
的数据库。 Then, once you've got all the Items, iterate over them and assign each to its parent Entity. Overall, it's best to tackle the actual problem (N+1 queries), instead of bending async code to implement it.总的来说,最好解决实际问题(N+1 个查询),而不是弯曲异步代码来实现它。 If you're writing something similar to an ORM, it may be worthwhile to explore existing implementations and how they deal with this well-researched issue.
如果您正在编写类似于 ORM 的东西,那么探索现有的实现以及它们如何处理这个经过充分研究的问题可能是值得的。
Maybe you could use a map function, a map function is async and can await.也许你可以使用 map function、map ZC1C425268E683854D1AB5074C17 和等待。
const data = res?.advancedResult?.data;
const temp = data.map(async(referential)=>{
return await EntityDAO.find({ query: { referential: referential?._id }
});
add here the rest...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.