¿Cuándo termina una función asincrónica? ¿Y por qué es tan difícil de responder esta pregunta?
Bueno, resulta que la comprensión de las funciones asincrónicas requiere una gran cantidad de conocimiento sobre cómo funciona JavaScript fundamentalmente.
Exploremos este concepto y aprendamos mucho sobre JavaScript en el proceso.
¿Estás listo? Vamonos.
¿Qué es el código asincrónico?
Por diseño, JavaScript es un lenguaje de programación sincrónico. Esto significa que cuando se ejecuta el código, JavaScript comienza en la parte superior del archivo y se ejecuta a través del código línea por línea, hasta que termina.
El resultado de esta decisión de diseño es que solo puede suceder una cosa a la vez.
Puede pensar en esto como si estuviera haciendo malabarismos con seis pelotas pequeñas. Mientras haces malabares, tus manos están ocupadas y no puedes manejar nada más.
Es lo mismo con JavaScript: una vez que el código se está ejecutando, tiene las manos ocupadas con ese código. A esto lo llamamos este tipo de bloqueo de código sincrónico . Porque efectivamente bloquea la ejecución de otro código.
Volvamos al ejemplo del malabarismo. ¿Qué pasaría si quisieras agregar otra bola? En lugar de seis bolas, querías hacer malabares con siete bolas. Eso puede ser un problema.
No querrás dejar de hacer malabares porque es muy divertido. Pero tampoco puedes ir a buscar otra pelota, porque eso significaría que tendrías que parar.
¿La solución? Delega el trabajo a un amigo o familiar. No están haciendo malabares, por lo que pueden ir a buscar la pelota por ti y luego lanzarla a tus malabares en un momento en que tu mano esté libre y estés listo para agregar otra pelota a mitad de los malabares.
Esto es lo que es el código asincrónico. JavaScript está delegando el trabajo a otra cosa y luego se ocupa de sus propios asuntos. Luego, cuando esté listo, recibirá los resultados del trabajo.
¿Quién hace el otro trabajo?
Muy bien, sabemos que JavaScript es sincrónico y perezoso. No quiere hacer todo el trabajo por sí mismo, por lo que lo dedica a otra cosa.
Pero, ¿quién es esta entidad misteriosa que funciona para JavaScript? ¿Y cómo se contrata para que funcione con JavaScript?
Bueno, echemos un vistazo a un ejemplo de código asincrónico.
const logName = () => { console.log("Han") } setTimeout(logName, 0) console.log("Hi there")
La ejecución de este código da como resultado la siguiente salida en la consola:
// in console Hi there Han
Bien. Que esta pasando?
Resulta que la forma en que trabajamos en JavaScript es utilizando funciones y API específicas del entorno. Y esta es una fuente de gran confusión en JavaScript.
JavaScript siempre se ejecuta en un entorno.
A menudo, ese entorno es el navegador. Pero también puede estar en el servidor con NodeJS. Pero, ¿cuál es la diferencia?
La diferencia, y esto es importante, es que el navegador y el servidor (NodeJS), en cuanto a funcionalidad, no son equivalentes. A menudo son similares, pero no son iguales.
Ilustremos esto con un ejemplo. Digamos que JavaScript es el protagonista de un libro de fantasía épica. Solo un niño de granja ordinario.
Ahora, digamos que este niño de la granja encontró dos trajes de armadura especial que le dieron poderes más allá de los suyos.
Cuando usaron la armadura del navegador, obtuvieron acceso a un cierto conjunto de capacidades.
Cuando usaron la armadura del servidor, obtuvieron acceso a otro conjunto de capacidades.
Estos trajes tienen cierta superposición, porque los creadores de estos trajes tenían las mismas necesidades en ciertos lugares, pero no en otros.
Esto es lo que es un medio ambiente. Un lugar donde se ejecuta el código, donde existen herramientas que se construyen sobre el lenguaje JavaScript existente. No son parte del lenguaje, pero la línea a menudo es borrosa porque usamos estas herramientas todos los días cuando escribimos código.
setTimeout, fetch y DOM son todos ejemplos de API web. (Puede ver la lista completa de API web aquí). Son herramientas que están integradas en el navegador y que están disponibles para nosotros cuando se ejecuta nuestro código.
Y como siempre ejecutamos JavaScript en un entorno, parece que estos son parte del lenguaje. Pero no lo son.
Entonces, si alguna vez se ha preguntado por qué puede usar fetch en JavaScript cuando lo ejecuta en el navegador (pero necesita instalar un paquete cuando lo ejecuta en NodeJS), esta es la razón. Alguien pensó que buscar era una buena idea y lo construyó como una herramienta para el entorno NodeJS.
¿Confuso? ¡Si!
Pero ahora finalmente podemos entender qué implica el trabajo de JavaScript y cómo se contrata.
Resulta que es el entorno el que asume el trabajo, y la forma de conseguir que el entorno haga ese trabajo es utilizar la funcionalidad que pertenece al entorno. Por ejemplo, fetch o setTimeout en el entorno del navegador.
¿Qué pasa con el trabajo?
Excelente. Entonces el medio ambiente asume el trabajo. ¿Y que?
En algún momento, es necesario recuperar los resultados. Pero pensemos en cómo funcionaría esto.
Volvamos al ejemplo del malabarismo desde el principio. Imagina que pides una pelota nueva y un amigo acaba de empezar a lanzarte la pelota cuando no estás listo.
Eso sería un desastre. Tal vez puedas tener suerte y atraparlo e incorporarlo a tu rutina de manera efectiva. Pero hay una gran posibilidad de que pueda hacer que se le caigan las bolas y se rompa su rutina. ¿No sería mejor si dieras instrucciones estrictas sobre cuándo recibir el balón?
Resulta que existen reglas estrictas sobre cuándo JavaScript puede recibir trabajo delegado.
Esas reglas se rigen por el ciclo de eventos e involucran la cola de microtask y macrotask. Sí, lo sé. Es mucho. Pero tengan paciencia conmigo.

Alright. So when we delegate asynchronous code to the browser, the browser takes and runs the code and takes on that workload. But there may be multiple tasks that are given to the browser, so we need to make sure that we can prioritise these tasks.
This is where the microtask queue and the macrotask queue come in play. The browser will take the work, do it, then place the result in one of the two queues based on the type of work it receives.
Promises, for example, are placed in the microtask queue and have a higher priority.
Events and setTimeout are examples of work that is put in the macrotask queue, and have a lower priority.
Now once the work is done, and is placed in one of the two queues, the event loop will run back and forth and check whether or not JavaScript is ready to receive the results.
Only when JavaScript is done running all its synchronous code, and is good and ready, will the event loop start picking from the queues and handing the functions back to JavaScript to run.
So let's take a look at an example:
setTimeout(() => console.log("hello"), 0) fetch("//someapi/data").then(response => response.json()) .then(data => console.log(data)) console.log("What soup?")
What will the order be here?
- Firstly, setTimeout is delegated to the browser, which does the work and puts the resulting function in the macrotask queue.
- Secondly fetch is delegated to the browser, which takes the work. It retrieves the data from the endpoint and puts the resulting functions in the microtask queue.
- Javascript logs out "What soup"?
- The event loop checks whether or not JavaScript is ready to receive the results from the queued work.
- When the console.log is done, JavaScript is ready. The event loop picks queued functions from the microtask queue, which has a higher priority, and gives them back to JavaScript to execute.
- After the microtask queue is empty, the setTimeout callback is taken out of the macrotask queue and given back to JavaScript to execute.
In console: // What soup? // the data from the api // hello
Promises
Now you should have a good deal of knowledge about how asynchronous code is handled by JavaScript and the browser environment. So let's talk about promises.
A promise is a JavaScript construct that represents a future unknown value. Conceptually, a promise is just JavaScript promising to return a value. It could be the result from an API call, or it could be an error object from a failed network request. You're guaranteed to get something.
const promise = new Promise((resolve, reject) => { // Make a network request if (response.status === 200) { resolve(response.body) } else { const error = { ... } reject(error) } }) promise.then(res => { console.log(res) }).catch(err => { console.log(err) })
A promise can have the following states:
- fulfilled - action successfully completed
- rejected - action failed
- pending - neither action has been completed
- settled - has been fulfilled or rejected
A promise receives a resolve and a reject function that can be called to trigger one of these states.
One of the big selling points of promises is that we can chain functions that we want to happen on success (resolve) or failure (reject):
- To register a function to run on success we use .then
- To register a function to run on failure we use .catch
// Fetch returns a promise fetch("//swapi.dev/api/people/1") .then((res) => console.log("This function is run when the request succeeds", res) .catch(err => console.log("This function is run when the request fails", err) // Chaining multiple functions fetch("//swapi.dev/api/people/1") .then((res) => doSomethingWithResult(res)) .then((finalResult) => console.log(finalResult)) .catch((err => doSomethingWithErr(err))
Perfect. Now let's take a closer look at what this looks like under the hood, using fetch as an example:
const fetch = (url, options) => { // simplified return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest() // ... make request xhr.onload = () => { const options = { status: xhr.status, statusText: xhr.statusText ... } resolve(new Response(xhr.response, options)) } xhr.onerror = () => { reject(new TypeError("Request failed")) } } fetch("//swapi.dev/api/people/1") // Register handleResponse to run when promise resolves .then(handleResponse) .catch(handleError) // conceptually, the promise looks like this now: // { status: "pending", onsuccess: [handleResponse], onfailure: [handleError] } const handleResponse = (response) => { // handleResponse will automatically receive the response, ¨ // because the promise resolves with a value and automatically injects into the function console.log(response) } const handleError = (response) => { // handleError will automatically receive the error, ¨ // because the promise resolves with a value and automatically injects into the function console.log(response) } // the promise will either resolve or reject causing it to run all of the registered functions in the respective arrays // injecting the value. Let's inspect the happy path: // 1. XHR event listener fires // 2. If the request was successfull, the onload event listener triggers // 3. The onload fires the resolve(VALUE) function with given value // 4. Resolve triggers and schedules the functions registered with .then
So we can use promises to do asynchronous work, and to be sure that we can handle any result from those promises. That is the value proposition. If you want to know more about promises you can read more about them here and here.
When we use promises, we chain our functions onto the promise to handle the different scenarios.
This works, but we still need to handle our logic inside callbacks (nested functions) once we get our results back. What if we could use promises but write synchronous looking code? It turns out we can.
Async/Await
Async/Await is a way of writing promises that allows us to write asynchronous code in a synchronous way. Let's have a look.
const getData = async () => { const response = await fetch("//jsonplaceholder.typicode.com/todos/1") const data = await response.json() console.log(data) } getData()
Nothing has changed under the hood here. We are still using promises to fetch data, but now it looks synchronous, and we no longer have .then and .catch blocks.
Async / Await is actually just syntactic sugar providing a way to create code that is easier to reason about, without changing the underlying dynamic.
Let's take a look at how it works.
Async/Await lets us use generators to pause the execution of a function. When we are using async / await we are not blocking because the function is yielding the control back over to the main program.
Then when the promise resolves we are using the generator to yield control back to the asynchronous function with the value from the resolved promise.
You can read more here for a great overview of generators and asynchronous code.
In effect, we can now write asynchronous code that looks like synchronous code. Which means that it is easier to reason about, and we can use synchronous tools for error handling such as try / catch:
const getData = async () => { try { const response = await fetch("//jsonplaceholder.typicode.com/todos/1") const data = await response.json() console.log(data) } catch (err) { console.log(err) } } getData()
Alright. So how do we use it? In order to use async / await we need to prepend the function with async. This does not make it an asynchronous function, it merely allows us to use await inside of it.
Failing to provide the async keyword will result in a syntax error when trying to use await inside a regular function.
const getData = async () => { console.log("We can use await in this function") }
Because of this, we can not use async / await on top level code. But async and await are still just syntactic sugar over promises. So we can handle top level cases with promise chaining:
async function getData() { let response = await fetch('//apiurl.com'); } // getData is a promise getData().then(res => console.log(res)).catch(err => console.log(err);
This exposes another interesting fact about async / await. When defining a function as async, it will always return a promise.
Using async / await can seem like magic at first. But like any magic, it's just sufficiently advanced technology that has evolved over the years. Hopefully now you have a solid grasp of the fundamentals, and can use async / await with confidence.
Conclusion
If you made it here, congrats. You just added a key piece of knowledge about JavaScript and how it works with its environments to your toolbox.
This is definitely a confusing subject, and the lines are not always clear. But now you hopefully have a grasp on how JavaScript works with asynchronous code in the browser, and a stronger grasp over both promises and async / await.
If you enjoyed this article, you might also enjoy my youtube channel. I currently have a web fundamentals series going where I go through HTTP, building web servers from scratch and more.
There's also a series going on building an entire app with React, if that is your jam. And I plan to add much more content here in the future going in depth on JavaScript topics.
And if you want to say hi or chat about web development, you could always reach out to me on twitter at @foseberg. Thanks for reading!