Answer the question
In order to leave comments, you need to log in
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');
})();
Answer the question
In order to leave comments, you need to log in
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');
});
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question