In the following snippet the resolution time is different when using promise#all and sequentially await for each promise. I want to deeply understand what is going on, since it seems to be a caveat when dealing with performance.
*Edit: added another case with no function invocation, probably I am missing something with how await works
// Code goes here
window.onload = function() {
let p = new Promise((res, rej) => {
setTimeout(() => {
res('p OK')
}, 5000);
})
let p2 = new Promise((res, rej) => {
setTimeout(() => {
res('p2 OK')
}, 5000);
})
let p3 = new Promise((res, rej) => {
setTimeout(() => {
res('p3 OK')
}, 5000);
})
async function pp() {
return new Promise((res, rej) => {
setTimeout(() => {
res('pp OK');
}, 5000);
});
}
async function a() {
let out = await Promise.all([p, pp()]);
return `#a ${out}`;
}
async function b() {
let out1 = await p;
let out2 = await pp();
return `#b ${out1} ${out2}`;
}
async function c() {
let out1 = await p;
let out2 = await p2;
let out3 = await p3;
return `#c ${out1} ${out2} ${out3}`;
}
let out1 = document.getElementById("out1");
let out2 = document.getElementById("out2");
let out32 = document.getElementById("out2");
const date = new Date().getSeconds();
a().then(x => console.log(x)).then(() => out1.innerHTML += `finished after ${new Date().getSeconds() - date}s`);
b().then(x => console.log(x)).then(() => out2.innerHTML += `finished after ${new Date().getSeconds() - date}s`);
c().then(x => console.log(x)).then(() => out3.innerHTML += `finished after ${new Date().getSeconds() - date}s`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<p id="out1">
Promise#all
</p>
<p id="out2">
Sequential awaits
</p>
<p id="out3">
Sequential awaits without executing fnc
</p>
</body>
</html>