I have the below code with a busy waiting method wrapped in SetTimeout. In my opinion it should run in asynchronously because of the SetTimeout. However, it takes 20 seconds to complete. Can you explain why?
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
function GetResultat() {
sleep(5000);
return Math.floor(Math.random()*11);
}
function HentTal() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
let resultat = GetResultat();
if (resultat== 10) {
throw new Error("Det fejlede big time");
}
if (resultat <= 7) {
resolve(resultat);
} else {
reject();
}
}
,0)
});
}
function resolved(value) {
console.log(value);
}
function rejected() {
console.log("No good");
}
Promise.all([HentTal(), HentTal(), HentTal(), HentTal()]).then(resolved).catch(rejected);