Skip to content

Commit fcd3181

Browse files
authored
Merge pull request #280 from vplentinax/microtask
Microtasks
2 parents c2a0dc3 + 82b3221 commit fcd3181

File tree

1 file changed

+47
-47
lines changed

1 file changed

+47
-47
lines changed
Lines changed: 47 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,112 +1,112 @@
11

2-
# Microtasks
2+
# Microtareas (Microtasks)
33

4-
Promise handlers `.then`/`.catch`/`.finally` are always asynchronous.
4+
Los manejadores o controladores (en adelante controladores) de promesas `.then`/`.catch`/`.finally` son siempre asincrónicos.
55

6-
Even when a Promise is immediately resolved, the code on the lines *below* `.then`/`.catch`/`.finally` will still execute before these handlers.
6+
Incluso cuando una promesa es inmediatamente resuelta, el código en las líneas *debajo de* `.then`/`.catch`/`.finally` se ejecutará antes que estos controladores.
77

8-
Here's a demo:
8+
Veamos una demostración:
99

1010
```js run
1111
let promise = Promise.resolve();
1212

13-
promise.then(() => alert("promise done!"));
13+
promise.then(() => alert("¡Promesa realizada!"));
1414

15-
alert("code finished"); // this alert shows first
15+
alert("código finalizado"); // esta alerta se muestra primero
1616
```
1717

18-
If you run it, you see `code finished` first, and then `promise done!`.
18+
Si ejecutas esto, verás `código finalizado` primero, y después `¡promesa realizada!`.
1919

20-
That's strange, because the promise is definitely done from the beginning.
20+
Es algo extraño, porque la promesa se realiza por completo desde el principio.
2121

22-
Why did the `.then` trigger afterwards? What's going on?
22+
¿Por qué `.then` se disparó después? ¿Qué está pasando?
2323

24-
## Microtasks queue
24+
## Cola de microtareas (Microtasks queue)
2525

26-
Asynchronous tasks need proper management. For that, the ECMA standard specifies an internal queue `PromiseJobs`, more often referred to as the "microtask queue" (ES8 term).
26+
Las tareas asincrónicas necesitan una gestión adecuada. Para ello, el estándar ECMA especifica una cola interna `PromiseJobs`, en ocasiones más conocida como "cola de microtareas" (término ES8).
2727

28-
As stated in the [specification](https://tc39.github.io/ecma262/#sec-jobs-and-job-queues):
28+
Como se indica en la [especificación](https://tc39.github.io/ecma262/#sec-jobs-and-job-queues):
2929

30-
- The queue is first-in-first-out: tasks enqueued first are run first.
31-
- Execution of a task is initiated only when nothing else is running.
30+
- La cola es first-in-first-out (FIFO), es decir, primero en entrar primero en salir: la tarea que entró primero en la cola, será la primera en ejecutarse.
31+
- La ejecución de una tarea se inicia sólo cuando *no* se está ejecutando nada más.
3232

33-
Or, to say more simply, when a promise is ready, its `.then/catch/finally` handlers are put into the queue; they are not executed yet. When the JavaScript engine becomes free from the current code, it takes a task from the queue and executes it.
33+
O, en palabras más simples, cuando una promesa está lista, sus controladores `.then/catch/finally` se ponen en la cola; ellos aún no se ejecutan. Cuando el motor de Javascript se libera del código actual, toma una tarea de la cola y la ejecuta.
3434

35-
That's why "code finished" in the example above shows first.
35+
Es por eso que el "código finalizado" en el ejemplo anterior se muestra primero.
3636

3737
![](promiseQueue.svg)
3838

39-
Promise handlers always go through this internal queue.
39+
Los controladoes de promesas siempre pasan por esta cola interna.
4040

41-
If there's a chain with multiple `.then/catch/finally`, then every one of them is executed asynchronously. That is, it first gets queued, then executed when the current code is complete and previously queued handlers are finished.
41+
Si hay una cadena con múltiples `.then/catch/finally`, entonces cada uno de ellos se ejecuta de forma asincrónica. Es decir, primero se pone en la cola, luego se ejecuta cuando se completa el código actual y se finalizan los controladores previamente en la cola.
4242

43-
**What if the order matters for us? How can we make `code finished` run after `promise done`?**
43+
**¿Qué pasa si lo que estamos pidiendo es importante? ¿Cómo podemos hacer que `código finalizado` se ejecute después de `¡promesa realizada!`?**
4444

45-
Easy, just put it into the queue with `.then`:
45+
Fácil, solo ponlo en la cola con `.then`:
4646

4747
```js run
4848
Promise.resolve()
49-
.then(() => alert("promise done!"))
50-
.then(() => alert("code finished"));
49+
.then(() => alert("promesa realiazada!"))
50+
.then(() => alert("código finalizado"));
5151
```
5252

53-
Now the order is as intended.
53+
Ahora el orden es el previsto.
5454

55-
## Unhandled rejection
55+
## Rechazo no controlado
5656

57-
Remember the `unhandledrejection` event from the article <info:promise-error-handling>?
57+
Recuerdas el evento `unhandledrejection` del artículo <info:promise-error-handling>?
5858

59-
Now we can see exactly how JavaScript finds out that there was an unhandled rejection.
59+
Ahora podemos ver exactamente cómo Javascript descubre que hubo un rechazo no controlado o *unhandled rejection*
6060

61-
**An "unhandled rejection" occurs when a promise error is not handled at the end of the microtask queue.**
61+
**Se produce un "rechazo no controlado" cuando no se maneja un error de promesa al final de la cola de microtareas.**
6262

63-
Normally, if we expect an error, we add `.catch` to the promise chain to handle it:
63+
Normalmente, si esperamos un error, agregamos `.catch` a la cadena de promesa para manejarlo:
6464

6565
```js run
66-
let promise = Promise.reject(new Error("Promise Failed!"));
66+
let promise = Promise.reject(new Error("¡Promesa fallida!"));
6767
*!*
68-
promise.catch(err => alert('caught'));
68+
promise.catch(err => alert('atrapado'));
6969
*/!*
7070

71-
// doesn't run: error handled
71+
// no se ejecuta: error controlado
7272
window.addEventListener('unhandledrejection', event => alert(event.reason));
7373
```
7474

75-
But if we forget to add `.catch`, then, after the microtask queue is empty, the engine triggers the event:
75+
Pero si olvidas añadir el `.catch`, entonces, después de que la cola de microtareas esté vacía, el motor activa el evento:
7676

7777
```js run
78-
let promise = Promise.reject(new Error("Promise Failed!"));
78+
let promise = Promise.reject(new Error("¡Promesa fallida!"));
7979

80-
// Promise Failed!
80+
// Promesa fallida!
8181
window.addEventListener('unhandledrejection', event => alert(event.reason));
8282
```
8383

84-
What if we handle the error later? Like this:
84+
¿Qué pasa si controlamos el error más tarde? Como esto:
8585

8686
```js run
87-
let promise = Promise.reject(new Error("Promise Failed!"));
87+
let promise = Promise.reject(new Error("¡Promesa fallida!"));
8888
*!*
89-
setTimeout(() => promise.catch(err => alert('caught')), 1000);
89+
setTimeout(() => promise.catch(err => alert('atrapado')), 1000);
9090
*/!*
9191

92-
// Error: Promise Failed!
92+
// Error: ¡Promesa fallida!
9393
window.addEventListener('unhandledrejection', event => alert(event.reason));
9494
```
9595

96-
Now, if we run it, we'll see `Promise Failed!` first and then `caught`.
96+
Ahora si lo ejecutamos, veremos `¡Promesa fallida!` primero y después `atrapado`.
9797

98-
If we didn't know about the microtasks queue, we could wonder: "Why did `unhandledrejection` handler run? We did catch and handle the error!"
98+
Si no supiéramos acerca de la cola de microtareas podríamos preguntarnos: "¿Por qué se ejecutó el controlador `unhandledrejection`? ¡Capturamos y manejamos el error!
9999

100-
But now we understand that `unhandledrejection` is generated when the microtask queue is complete: the engine examines promises and, if any of them is in the "rejected" state, then the event triggers.
100+
Pero ahora entendemos que `unhandledrejection` se genera cuando se completa la cola de microtareas: el motor examina las promesas y, si alguna de ellas está en el estado "rechazado", entonces el evento se dispara.
101101

102-
In the example above, `.catch` added by `setTimeout` also triggers. But it does so later, after `unhandledrejection` has already occurred, so it doesn't change anything.
102+
En el ejemplo anterior, `.catch` agregado por `setTimeout` también se dispara. Pero lo hace más tarde, después de que `unhandledrejection` ya ha ocurrido, por lo que no cambia nada.
103103

104-
## Summary
104+
## Resumen
105105

106-
Promise handling is always asynchronous, as all promise actions pass through the internal "promise jobs" queue, also called "microtask queue" (ES8 term).
106+
El control de promesas siempre es asíncrono, ya que todas las acciones de promesa pasan por la cola interna de "PromiseJobs", también llamada "cola de microtareas" (término ES8).
107107

108-
So `.then/catch/finally` handlers are always called after the current code is finished.
108+
Entonces, los controladores `.then/catch/finally` siempre se llaman después de que el código actual ha finalizado.
109109

110-
If we need to guarantee that a piece of code is executed after `.then/catch/finally`, we can add it into a chained `.then` call.
110+
Si necesitamos garantizar que un código se ejecute después de `.then/catch/finally`, podemos agregarlo a una llamada encadenada `.then`.
111111

112-
In most Javascript engines, including browsers and Node.js, the concept of microtasks is closely tied with the "event loop" and "macrotasks". As these have no direct relation to promises, they are covered in another part of the tutorial, in the article <info:event-loop>.
112+
En la mayoría de los motores de Javascript, incluidos los navegadores y Node.js, el concepto de microtareas está estrechamente relacionado con el "bucle de eventos" o "event loop" y "macrotareas" o "macrotasks". Como estos no tienen relación directa con las promesas, están cubiertos en otra parte del tutorial, en el artículo <info:event-loop>.

0 commit comments

Comments
 (0)