You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the task<info:task/animate-circle>an animated growing circle is shown.
4
+
En la tarea<info:task/animate-circle>se muestra un círculo creciente animado.
5
5
6
-
Now let's say we need not just a circle, but to show a message inside it. The message should appear *after* the animation is complete (the circle is fully grown), otherwise it would look ugly.
6
+
Ahora digamos que necesitamos no solo un círculo, sino mostrar un mensaje dentro de él. El mensaje debería aparecer *después* de que la animación esté completa (el círculo es desarrollado completamente), de lo contrario se vería feo.
7
7
8
-
In the solution of the task, the function`showCircle(cx, cy, radius)`draws the circle, but gives no way to track when it's ready.
8
+
En la solución de la tarea, la función`showCircle(cx, cy, radius)`dibuja el círculo, pero no hay forma de saber cuando lo termina.
9
9
10
-
Add a callback argument: `showCircle(cx, cy, radius, callback)`to be called when the animation is complete. The`callback`should receive the circle`<div>`as an argument.
10
+
Agrega un argumento callback: `showCircle(cx, cy, radius, callback)`que se llamará cuando se complete la animación. El`callback`debería recibir el círculo`<div>`como argumento.
11
11
12
-
Here's the example:
12
+
Aqui el ejemplo:
13
13
14
14
```js
15
15
showCircle(150, 150, 100, div=> {
16
16
div.classList.add('message-ball');
17
-
div.append("Hello, world!");
17
+
div.append("Hola, mundo!");
18
18
});
19
19
```
20
20
21
-
Demo:
21
+
Demostración:
22
22
23
23
[iframe src="solution" height=260]
24
24
25
-
Take the solution of the task<info:task/animate-circle>as the base.
25
+
Toma la solución de la tarea<info:task/animate-circle>como base.
# Introducción: funciones de retrollamadas (callbacks)
1
2
3
+
```warn header="Usamos métodos de navegador en estos ejemplos"
4
+
Para demostrar el uso de callbacks, promesas y otros conceptos abstractos, utilizaremos algunos métodos de navegador: específicamente, carga de scripts y simples manipulaciones de documentos.
2
5
3
-
# Introduction: callbacks
6
+
Si no estás familiarizado con estos métodos, y los ejemplos son confusos, puedes leer algunos capítulos de esta [sección](/document) del tutorial.
4
7
5
-
```warn header="We use browser methods in examples here"
6
-
To demonstrate the use of callbacks, promises and other abstract concepts, we'll be using some browser methods: specifically, loading scripts and performing simple document manipulations.
7
-
8
-
If you're not familiar with these methods, and their usage in the examples is confusing, you may want to read a few chapters from the [next part](/document) of the tutorial.
9
-
10
-
Although, we'll try to make things clear anyway. There won't be anything really complex browser-wise.
8
+
Sin embargo, intentaremos aclarar las cosas de todos modos. No habrá nada en cuanto al navegador realmente complejo.
11
9
```
12
10
13
-
Many functions are provided by JavaScript host environments that allow you to schedule *asynchronous* actions. In other words, actions that we initiate now, but they finish later.
11
+
Muchas funciones son proporcionadas por el entorno de host de Javascript que permiten programar acciones *asíncronas*. En otras palabras, acciones que iniciamos ahora, pero que terminan más tarde.
14
12
15
-
For instance, one such function is the `setTimeout` function.
13
+
Por ejemplo, una de esas funciones es la función `setTimeout`.
16
14
17
-
There are other real-world examples of asynchronous actions, e.g. loading scripts and modules (we'll cover them in later chapters).
15
+
Hay otros ejemplos del mundo real de acciones asincrónicas, p. ej.: la carga de scripts y módulos (a cubrirse en capítulos posteriores).
18
16
19
-
Take a look at the function`loadScript(src)`, that loads a script with the given `src`:
17
+
Echa un vistazo a la función`loadScript(src)`, que carga un script dado: `src`
20
18
21
19
```js
22
20
functionloadScript(src) {
23
-
//creates a <script> tag and append it to the page
24
-
//this causes the script with given src to start loading and run when complete
21
+
//crea una etiqueta <script> y la agrega a la página
22
+
//esto hace que el script dado: src comience a cargarse y ejecutarse cuando se complete
25
23
let script =document.createElement('script');
26
24
script.src= src;
27
25
document.head.append(script);
28
26
}
29
27
```
30
28
31
-
It appends to the document the new, dynamically created, tag `<script src="…">`with given`src`. The browser automatically starts loading it and executes when complete.
29
+
Anexa al documento la nueva etiqueta, creada dinámicamente, `<script src =" ... ">`con el`src` dado. El navegador comienza a cargarlo automáticamente y se ejecuta cuando se completa.
32
30
33
-
We can use this function like this:
31
+
Esta función la podemos usar así:
34
32
35
33
```js
36
-
//load and execute the script at the given path
34
+
//cargar y ejecutar el script en la ruta dada
37
35
loadScript('/my/script.js');
38
36
```
39
37
40
-
The script is executed "asynchronously", as it starts loading now, but runs later, when the function has already finished.
38
+
El script se ejecuta "asincrónicamente", ya que comienza a cargarse ahora, pero se ejecuta más tarde, cuando la función ya ha finalizado.
41
39
42
-
If there's any code below `loadScript(…)`, it doesn't wait until the script loading finishes.
40
+
El código debajo de `loadScript (...)`, no espera que finalice la carga del script.
43
41
44
42
```js
45
43
loadScript('/my/script.js');
46
-
//the code below loadScript
47
-
//doesn't wait for the script loading to finish
44
+
//el código debajo de loadScript
45
+
//no espera a que finalice la carga del script
48
46
// ...
49
47
```
50
48
51
-
Let's say we need to use the new script as soon as it loads. It declares new functions, and we want to run them.
49
+
Digamos que necesitamos usar el nuevo script tan pronto como se cargue. Declara nuevas funciones, y queremos ejecutarlas.
52
50
53
-
But if we do that immediately after the`loadScript(…)` call, that wouldn't work:
51
+
Si hacemos eso inmediatamente después de llamar a`loadScript (...)`, no funcionará:
54
52
55
53
```js
56
-
loadScript('/my/script.js'); //the script has "function newFunction() {…}"
54
+
loadScript('/my/script.js'); //el script tiene a "function newFunction() {…}"
57
55
58
56
*!*
59
-
newFunction(); // no such function!
57
+
newFunction(); // no hay dicha función!
60
58
*/!*
61
59
```
62
60
63
-
Naturally, the browser probably didn't have time to load the script. As of now, the `loadScript`function doesn't provide a way to track the load completion. The script loads and eventually runs, that's all. But we'd like to know when it happens, to use new functions and variables from that script.
61
+
Naturalmente, el navegador probablemente no tuvo tiempo de cargar el script. Hasta el momento, la función `loadScript`no proporciona una forma de rastrear la finalización de la carga. El script se carga y finalmente se ejecuta, eso es todo. Pero nos gustaría saber cuándo sucede, para usar las funciones y variables nuevas de dicho script.
64
62
65
-
Let's add a`callback`function as a second argument to `loadScript`that should execute when the script loads:
63
+
Agreguemos una función`callback`como segundo argumento para `loadScript`que debería ejecutarse cuando se carga el script:
66
64
67
65
```js
68
66
functionloadScript(src, *!*callback*/!*) {
@@ -77,19 +75,19 @@ function loadScript(src, *!*callback*/!*) {
77
75
}
78
76
```
79
77
80
-
Now if we want to call new functions from the script, we should write that in the callback:
78
+
Ahora, si queremos llamar las nuevas funciones desde el script, deberíamos escribirlo en la callback:
81
79
82
80
```js
83
81
loadScript('/my/script.js', function() {
84
-
//the callback runs after the script is loaded
85
-
newFunction(); //so now it works
82
+
//la callback se ejecuta luego que se carga el script
83
+
newFunction(); //ahora funciona
86
84
...
87
85
});
88
86
```
89
87
90
-
That's the idea: the second argument is a function (usually anonymous) that runs when the action is completed.
88
+
Esa es la idea: el segundo argumento es una función (generalmente anónima) que se ejecuta cuando se completa la acción.
91
89
92
-
Here's a runnable example with a real script:
90
+
Aquí un ejemplo ejecutable con un script real:
93
91
94
92
```js run
95
93
functionloadScript(src, callback) {
@@ -101,39 +99,39 @@ function loadScript(src, callback) {
alert( _ ); //function declared in the loaded script
102
+
alert(`Genial, el script ${script.src}está cargado`);
103
+
alert( _ ); //función declarada en el script cargado
106
104
});
107
105
*/!*
108
106
```
109
107
110
-
That's called a "callback-based" style of asynchronous programming. A function that does something asynchronously should provide a`callback`argument where we put the function to run after it's complete.
108
+
Eso se llama programación asincrónica "basado en callback". Una función que hace algo de forma asincrónica debería aceptar un argumento de`callback`donde ponemos la función por ejecutar después de que se complete.
111
109
112
-
Here we did it in `loadScript`, but of course it's a general approach.
110
+
Aquí lo hicimos en `loadScript`, pero por supuesto es un enfoque general.
113
111
114
-
## Callback in callback
112
+
## Callback en una callback
115
113
116
-
How can we load two scripts sequentially: the first one, and then the second one after it?
114
+
¿Cómo podemos cargar dos scripts secuencialmente: el primero y después el segundo al cargarse el primero?
117
115
118
-
The natural solution would be to put the second `loadScript`call inside the callback, like this:
116
+
La solución natural sería poner la segunda llamada `loadScript`dentro de la callback, así:
119
117
120
118
```js
121
119
loadScript('/my/script.js', function(script) {
122
120
123
-
alert(`Cool, the${script.src}is loaded, let's load one more`);
121
+
alert(`Genial, el${script.src}está cargado, carguemos uno más`);
124
122
125
123
*!*
126
124
loadScript('/my/script2.js', function(script) {
127
-
alert(`Cool, the second script is loaded`);
125
+
alert(`Genial, el segundo script está cargado`);
128
126
});
129
127
*/!*
130
128
131
129
});
132
130
```
133
131
134
-
After the outer `loadScript`is complete, the callback initiates the inner one.
132
+
Una vez que se completa el `loadScript`externo, la callback inicia el interno.
So, every new action is inside a callback. That's fine for few actions, but not good for many, so we'll see other variants soon.
152
+
Entonces, cada nueva acción está dentro de una callback. Eso está bien para algunas acciones, pero no es bueno para todas, así que pronto veremos otras variantes.
155
153
156
-
## Handling errors
154
+
## Manejo de errores
157
155
158
-
In the above examples we didn't consider errors. What if the script loading fails? Our callback should be able to react on that.
156
+
En los ejemplos anteriores no consideramos los errores. ¿Qué pasa si falla la carga del script? Nuestra callback debería poder reaccionar ante eso.
159
157
160
-
Here's an improved version of`loadScript`that tracks loading errors:
158
+
Aquí una versión mejorada de`loadScript`que rastrea los errores de carga:
161
159
162
160
```js
163
161
functionloadScript(src, callback) {
@@ -166,39 +164,39 @@ function loadScript(src, callback) {
3. We load `3.js`, then if there's no error -- do something else `(*)`.
229
+
En el código de arriba:
230
+
1. Cargamos `1.js`, entonces si no hay error.
231
+
2. Cargamos `2.js`, entonces si no hay error.
232
+
3. Cargamos `3.js`, luego, si no hay ningún error, haga otra cosa `(*)`.
233
+
234
+
235
+
A medida que las llamadas se anidan más, el código se vuelve más profundo y difícil de administrar, especialmente si tenemos un código real en lugar de '...' que puede incluir más bucles, declaraciones condicionales, etc.
235
236
236
-
As calls become more nested, the code becomes deeper and increasingly more difficult to manage, especially if we have real code instead of `...` that may include more loops, conditional statements and so on.
237
+
A esto se le llama "callback hell" o "Pirámide de Doom".
237
238
238
-
That's sometimes called "callback hell" or "pyramid of doom."
The "pyramid" of nested calls grows to the right with every asynchronous action. Soon it spirals out of control.
289
+
La "pirámide" de llamadas anidadas crece a la derecha con cada acción asincrónica. Pronto se sale de control.
267
290
268
-
So this way of coding isn't very good.
291
+
Entonces, esta forma de codificación no es tan buena.
269
292
270
-
We can try to alleviate the problem by making every action a standalone function, like this:
293
+
Trataremos de aliviar el problema haciendo cada acción una función independiente, asi:
271
294
272
295
```js
273
296
loadScript('1.js', step1);
@@ -294,17 +317,18 @@ function step3(error, script) {
294
317
if (error) {
295
318
handleError(error);
296
319
} else {
297
-
// ...continue after all scripts are loaded (*)
320
+
// ...continua despues que se han cargado todos los scripts (*)
298
321
}
299
322
};
300
323
```
301
324
302
-
See? It does the same, and there's no deep nesting now because we made every action a separate top-level function.
325
+
¿Lo Ves? Hace lo mismo, y ahora no hay anidamiento profundo porque convertimos cada acción en una función de nivel superior separada.
326
+
327
+
Funciona, pero el código parece una hoja de cálculo desgarrada. Es difícil de leer, y habrías notado que hay que saltar de un lado a otro mientras lees. Es un inconveniente, especialmente si el lector no está familiarizado con el código y no sabe dónde dirigirse.
303
328
304
-
It works, but the code looks like a torn apart spreadsheet. It's difficult to read, and you probably noticed that one needs to eye-jump between pieces while reading it. That's inconvenient, especially if the reader is not familiar with the code and doesn't know where to eye-jump.
305
329
306
-
Also, the functions named`step*`are all of single use, they are created only to avoid the "pyramid of doom." No one is going to reuse them outside of the action chain. So there's a bit of namespace cluttering here.
330
+
Además, las funciones llamadas`step*`son de un solo uso, son para evitar la "Pirámide de funciones callback". Nadie los reutilizará fuera de la cadena de acción. Así que hay muchos nombres abarrotados aquí.
307
331
308
-
We'd like to have something better.
332
+
Nos gustaría tener algo mejor.
309
333
310
-
Luckily, there are other ways to avoid such pyramids. One of the best ways is to use "promises," described in the next chapter.
334
+
Afortunadamente, podemos evitar tales pirámides. Una de las mejores formas es usando "promesas", descritas en el próximo capítulo.
0 commit comments