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

1

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

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

    
asked by anonymous 09.04.2018 / 19:10

2 answers

1

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

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

Warning that synchronous / asynchronous does not have to do with multi-threading.

    
09.04.2018 / 19:47
0

You write "linearly" rather than 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();
    
09.04.2018 / 19:45