D
D
DailyDDose2018-02-10 17:40:39
JavaScript
DailyDDose, 2018-02-10 17:40:39

Async await from the inside - how does it work?

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
 
(async() => {
    setTimeout(() => console.log('1000'), 1000);
    await sleep(5000);
    console.log('5');
})();

Why is 1000 printed before 5?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-10
@DailyDDose

async/await is just a convenient wrapper around promises. You can read more about async/await here .
1000 is displayed earlier because the function, thanks to the use of the await keyword , waits for the response from the Promise returned by the sleep function and only then continues execution.
In V8, async/await as well as Promise are implemented in JavaScript . The implementation can be found here .
As you can see, it is implemented on generators.
An analogue of your example without using async/await :

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

(() => {
    setTimeout(() => console.log('1000'), 1000);
    sleep(5000).then(() => {
      console.log('5');
    });
})();

Also, an async function always returns a Promise , even if you don't return anything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question