Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Promise.all does not seem to run promises in parallel

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);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Javascript is single thread… it means that you cannot run two processes in the CPU at the same time. Your sleep functions are executed inside an async execution. But once it starts executing, it blocks the single thread for 5 seconds. The other 3 sleeps keep waiting in the queue for the chance to take the CPU single thread.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading