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 resolved runs before main process finished

I have two function which have different process time, lets say one() takes 1 second, two() takes 0.3 second. I trying to run function one() runs first and then do function two() using promise. in my code i set two() as resolved, but actually its runs function two() before one() finished.

sorry my english not that good, i hope you understand my context here

main();

function main() {
    let promise = new Promise(function(resolved) {
        one();
        resolved();
    });

    promise.then(two());
}

function one() {
    setTimeout(() => {
        console.log("ONE");
    }, 1000);
}

function two() {
    setTimeout(() => {
        console.log("TWO");
    }, 300);
}

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

>Solution :

You are running one first, log TWO before ONE is because method one takes more timeout.

You could change function one to an async function, resolve it after the timeout, and let function two wait for its execution to finish.

Option #1: You can use async/await to ensure one is resolved before executing function two.

main();

async function main() {
    await one();
    two();
}

function one() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log("ONE");
            resolve();
        }, 1000);
    });
}

function two() {
    setTimeout(() => {
        console.log("TWO");
    }, 300);
}

Option #2: Use promise.then

main();

function main() {
    one().then(two);
}

function one() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log("ONE");
            resolve();
        }, 1000);
    });
}

function two() {
    setTimeout(() => {
        console.log("TWO");
    }, 300);
}
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