Home > Blockchain >  How to handle asynchronous call in javascript - print numbers with delay using promises
How to handle asynchronous call in javascript - print numbers with delay using promises

Time:10-08

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

CodePudding user response:

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

CodePudding user response:

A cleaner solution would be to implement a wait function. Then you can write more readable code.

const wait = async ms => new Promise(resolve => setTimeout(resolve, ms));

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

async function count(n) {
  for (let i = 1; i <= n; i  ) {
    await wait(1000);
    console.log(i);
  }
}

disp();

CodePudding user response:

Or, with fewer functions, @gre_gor's solution would look like this:

async function disp(n) {
  console.log("start")
  for (let i = 1; i <= n; i  ) {
    await new Promise(resolve => setTimeout(resolve, 1000));
    console.log(i);
  }
  console.log("end")
}

disp(10);

  • Related