0

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?

Community
  • 1
  • 1
SuicideSheep
  • 5,260
  • 19
  • 64
  • 117
  • Possible duplicate of [Javascript Await/Async Feature - What if you do not have the await word in the function?](https://stackoverflow.com/questions/47911869/javascript-await-async-feature-what-if-you-do-not-have-the-await-word-in-the-f) The first answer should satisfy your question. – Nico Mar 16 '18 at 03:25
  • 1
    NOTHING turns an asynchronous function into a synchronous one - just a moments thought about it, and you'd understand why - i.e. if something takes an unknown amount of time, how can the amount of time it takes be known – Jaromanda X Mar 16 '18 at 03:37
  • 2
    Put a `console.log(4)` after your line with `asyncCall()`. – Bergi Mar 16 '18 at 03:39
  • Truthfully it does not make them synchronous; it only makes the code useable in a syntactic style that is like synchronous code. – l3l_aze Mar 16 '18 at 03:53
  • Your `asyncCall` function can also be written like `var asyncCall = _ => (console.log(1), resolveAfter2Seconds()).then(console.log).then( _ => console.log(3));`. It's totally asynchronous. – Redu Mar 16 '18 at 13:41

0 Answers0