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

How to handle asynchronous call in javascript – print numbers with delay using promises

I am trying to create a function which displays numbers 1 to 10 and prints each number by delay. Like print 1 after 1 second, 2 after 2 seconds upto 10. Also have to print start and end before the number printing and after.

Trying to create a promise and use async await to achieve this. However not able to print correctly "end" after the function.

When trying to resolve the promise, it is getting resolved before the settimout operation.

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

async function disp(){
    console.log("start")
    await promise();
    console.log("end")
}

function promise(){
    return new Promise((resolve, reject) => {
        for(let i=1;i<10;i++){
            setTimeout(() => {
                console.log(i);
            }, i*1000);
        }
        //resolve();
    })
}


disp();

>Solution :

Promise is not settling i.e It is neither resolving or rejecting so it gonna stay in pending state. All you have to do is to settle the promise after i reaches the final count

async function disp() {
    console.log('start');
    await promise();
    console.log('end');
}

function promise() {
    return new Promise((resolve, reject) => {
        const upto = 10;
        for (let i = 1; i <= upto; i++) {
            setTimeout(() => {
                console.log(i);
                if (i === upto) resolve();  // CHANGE
            }, i * 1000);
        }
    });
}

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