DEV Community

Cristian Fernando
Cristian Fernando

Posted on

4 3

Paracetamol.js💊| #132: Explica este código JavaScript

¿Cuál es el orden de ejecución del siguiente código JavaScript?

Dificultad: Avanzado

async function asyncFunc() {
  console.log('asyncFunc() starts'); 
  return 'abc';
}

asyncFunc().
  then(x => { 
    console.log(`Resolved: ${x}`);
  });
console.log('Task ends'); 
Enter fullscreen mode Exit fullscreen mode

A. asyncFunc() starts, Resolved: abc, Task ends
B. Task ends, asyncFunc() starts, Resolved: abc
C. asyncFunc() starts, Task ends, Resolved: abc
D. Ninguna de las anteriores

Respuesta en el primer comentario.


Top comments (1)

Collapse
 
duxtech profile image
Cristian Fernando

Respuesta:
C. asyncFunc() starts, Task ends, Resolved: abc

  • El interprete de JavaScript llega a la línea donde se llama a la función asyncFunc y muestra por consola asyncFunc() starts.
  • Como asyncFunc es una función asíncrona, por definición regresará una promesa, por ello dicha promesa pasará a almacenarse temporalmente en el Micro Task Queue de JavaScript.
  • Salimos de la función y ahora mostramos por consola Task ends.
  • Posteriormente el Even Loop verifica que el Call Stack esta vacío y desde el Micro Task Queue pasamos la promesa para su ejecución.
  • Finalmente mostramos por consola Resolved: abc y el programa termina.

Recuerda que el Micro Task Queue en JavaScript es exclusivo para manipular promesas a diferencia por ejemplo del Task Queue que administra Web API's.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay