How to use await instead of . then() in Javascript?

Asked

Viewed 109 times

3

I have this asynchronous code:

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


async function umPorSegundo(){
    console.log(await delay(), '1s')
    console.log(await delay(), '2s')
    console.log(await delay(), '3s')
}

umPorSegundo();

The delay is done correctly, but the console always returns undefined before. How to make it return only the seconds?

  • 1

    console.log(await delay() || '1s');

1 answer

3


The console is logging in undefined because the function delay returns nothing (what is undefined).

For example:

function test() {
  // Não retorna nada.
}

console.log(test()); // undefined

If you want to modify the function delay to return the seconds, you will need to change her code:

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

In that case, the Promise will be solving the value 1000 (1000 milliseconds is equal to 1 second). You can modify the resolve so that the promise will solve any other value...

To learn more about the Promises, read here.

Browser other questions tagged

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