It seems like you are running more code in the parallel version
// The normal version
let normal = await ContentRepo.geBySkillIdWithSourceFiltered(
[chosenSkillsArr[0].sid!],
readContentIds,
body.isVideoIncluded,
true,
true
);
// The code inside the parallel version:
chosenSkillsArr.map(async (skill: IScrapeSkillDocument) => {
const result = await ContentRepo.geBySkillIdWithSourceFiltered(
[skill.sid!],
readContentIds,
body.isVideoIncluded,
true,
true
);
})
[chosenSkillsArr[0].sid!], vs chosenSkillsArr.map()
For the parallel version, you are putting the function call (ContentRepo.geBySkillIdWithSourceFiltered
) inside a loop. That's why it is slower.
For the question about running promises in parallel:
Like Promise.all
, Promise.allSettled
await multiple promises. It doesn't care about what order they resolve, or whether the computations are running in parallel. They both do not guarantee concurrency nor the opposite. Their task is just to ensure all the promises passed to it are handled.
So you can't manually guarantee the parallelism of promise execution
Here is a really interesting article explaining parallelism and Promise.All
and how browser Nodejs API differs from Nodejs API installed on your computer in terms of parallelism.
Here is the extract of the article's conclusion:
JavaScript runtime is single-threaded. We do not have access to thread in JavaScript. Even if you have multi-core CPU you still can't run tasks in parallel using JavaScript. But, the browser/NodeJS uses C/C++ (!) where they have access to thread. So, they can achieve parallelism.
Side Note:
There is one subtle difference:
Promise.all: Resolves only when all promises passed to it resolves else it will reject with the first rejected promise error.
Promise.allSettled: Will always get resolved with an array having info about resolved and rejected promises.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…