Skip to content
Advertisement

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.

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

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement