DEV Community

Cristian Fernando
Cristian Fernando

Posted on

3 1

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

Explica este código JavaScript

const myPromise = () => Promise.resolve('I have resolved!')

function firstFunction() {
  myPromise().then(res => console.log(res))
  console.log('second')
}

async function secondFunction() {
  console.log(await myPromise())
  console.log('second')
}

firstFunction()
secondFunction()
Enter fullscreen mode Exit fullscreen mode
  • A: I have resolved!, second y I have resolved!, second
  • B: second, I have resolved! y second, I have resolved!
  • C: I have resolved!, second y second, I have resolved!
  • D: second, I have resolved! y I have resolved!, second

Respuesta el el primer comentario.


Top comments (1)

Collapse
 
duxtech profile image
Cristian Fernando • Edited

Respuesta
D: second, I have resolved! y I have resolved!, second

firstFunction es una función simple que llama a myPromise usando el método then propio de las promesas. Por Event Loop las promesas pasan al Task Queue entonces primero ejecutamos el console.log y mostramos second por consola, ahora el Call Stack esta vacio y la promesa que estaba en la Task Queue pasa al Call Stack y resolvemos la promesa mostrando 'I have resolved!'.

secondFunction es una función asíncrona, al llamar a myPromise con await esperamos el tiempo necesario para que la promesa se ejecute, entonces mostramos primero por consola 'I have resolved!' y luego second.

Cuando tenemos sintaxis async await escribimos código de manera síncrona pero se ejecuta de manera asíncrona.

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay