Javascript: What is the difference between asynchronous functions and normal functions

Asked

Viewed 1,933 times

3

I want to know the difference between using a async function and a function only. Of course, with asynchronous functions one can use await and they return a Promise.

But is there any other effect? Is there any difference in the way the code is executed?

2 answers

3


When a normal function is executed, it is executed sequentially. That is, if you have two functions A() and B() and you run them in that order, function B() will only be called when function A() ends its execution.

By contrast, if you have an asynchronous function A() (for example, that performs an I/O operation or other blocking operation), this can be called and while the operation is performed you can perform another function B() (asynchronous or not) in the main context (main thread). Later, the A() function will return its value when the operation is complete and the main thread is available for this.

Attention that synchronous/asynchronous has nothing to do with multi-threading.

  • I had the impression that this is what was happening, but I couldn’t find anything on the internet about it. Thank you.

0

You write "linear" and not with so many callbacks... Example:

function resolveDepoisDe2Segundos() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolvido');
    }, 2000);
  });
}

async function teste() {
  console.log('inicio');
  var resultadoAwait = await resolveDepoisDe2Segundos();
  var resultadoPromisse = resolveDepoisDe2Segundos();
  console.log('resultado await', resultadoAwait);
  console.log('resultado promisse then', resultadoPromisse.then(function(resultado){
    console.log('resultado promisse resolved', resultado);
  }));
  console.log('fim');
}

teste();

Browser other questions tagged

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