From this medium article, it says
This is an example of a synchronous code:
console.log('1')
console.log('2')
console.log('3')
This code will reliably log “1 2 3".
Asynchronous requests will wait for a timer to finish or a request to respond while the rest of the code continues to execute. Then when the time is right a callback will spring these asynchronous requests into action.
console.log('1')
setTimeout(function afterTwoSeconds() {
console.log('2')
}, 2000)
console.log('3')
//prints 1 3 2
And I came across Async/Await
by using below code
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('2');
}, 2000);
});
}
async function asyncCall() {
console.log('1');
var result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
console.log('3');
}
asyncCall();
Not sure if I understand wrongly but seems to me that keyword async
and await
turns a Asynchronous
function into a synchronous
function?