.then() in Async/Await

Asked

Viewed 82 times

1

How I would transform the following function using async/await?

const delay = () => new Promise(resolve => setTimetout(resolve, 1000);

function umPorSegundo() {
   delay().then(() => {
      console.log('1s');

      delay().then(() => {
         console.log('2s');

         delay().then(() => {
            console.log('3s');
         });
      });
   });
}

umPorSegundo();

I know it would be something like this:

const delay = () => new Promise(resolve => setTimeout(resolve, 1000));

async function umPorSegundo(){
    console.log(await delay());
    console.log(await delay());
    console.log(await delay());
}

umPorSegundo();

However, I don’t know how to pass a different string to each await.

1 answer

2


You are almost there! What is missing is having a function that calls itself, and then passing a counter to increase the values...

You can do it like this:

const delay = (str) => new Promise(resolve => setTimeout(() => resolve(str), 1000));

async function umPorSegundo(nr = 0) {
  const segundos = await delay(nr) + 's';
  console.log(segundos);
  return umPorSegundo(nr + 1);
}

umPorSegundo();

  • 1

    That’s it! That’s what I really needed, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.