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
As we know, `fetch`returns a promise. And JavaScript generally has no concept of "aborting" a promise. So how can we abort a`fetch`?
4
+
Como sabemos `fetch`devuelve una promesa, y generalmente JavaScript no tiene un concepto de "abortar" una promesa. Entonces, ¿cómo podemos abortar una llamada al método`fetch`?
5
5
6
-
There's a special built-in object for such purposes: `AbortController`, that can be used to abort not only`fetch`, but other asynchronous tasks as well.
6
+
Existe para esto de forma nativa un objeto especial: `AbortController`, este puede ser utilizado para abortar una tarea`fetch`, así como otras tareas asincrónicas.
7
7
8
-
The usage is pretty simple:
8
+
Su uso es muy sencillo:
9
9
10
-
-Step 1: create a controller:
10
+
-Paso 1: crear un controlador:
11
11
12
12
```js
13
13
let controller =newAbortController();
14
14
```
15
15
16
-
A controller is an extremely simple object.
16
+
Este controlador es un objeto extremadamente simple.
17
17
18
-
-It has a single method `abort()`, and a single property`signal`.
-La propiedad `controller.signal.aborted`toma el valor`true`.
22
22
23
-
All parties interested to learn about `abort()`call set listeners on `controller.signal` to track it.
23
+
Todas las partes interesadas en estar al tanto de una llamada a `abort()`realizan un seguimiento a la propiedad `controller.signal`.
24
24
25
-
Like this (without `fetch` yet):
25
+
Tal como se muestra a continuación (por ahora sin `fetch`):
26
26
27
27
```js run
28
28
let controller = new AbortController();
@@ -36,7 +36,7 @@ The usage is pretty simple:
36
36
alert(signal.aborted); // true
37
37
```
38
38
39
-
-Step2:pass the `signal`property to `fetch` option:
39
+
-Paso2:Se pasa la propiedad `signal`en la opción de `fetch`:
40
40
41
41
```js
42
42
let controller = new AbortController();
@@ -45,20 +45,20 @@ The usage is pretty simple:
45
45
});
46
46
```
47
47
48
-
The `fetch`method knows how to work with`AbortController`, it listens to`abort`on`signal`.
48
+
El método `fetch`conoce como funciona `AbortController`, el escucha por`abort`en`signal`.
49
49
50
-
-Step3:to abort, call `controller.abort()`:
50
+
-Paso3:Se llama al método `controller.abort()` para abortar:
51
51
52
52
```js
53
53
controller.abort();
54
54
```
55
55
56
-
We're done: `fetch` gets the event from `signal` and aborts the request.
56
+
Y así`fetch`obtiene el evento desde`signal`y aborta la solicitud.
57
57
58
-
When a fetch is aborted, its promise rejects with an error `AbortError`, so we should handle it, e.g. in `try..catch`:
58
+
Cuando un fetch es abortado su promesa es rechazada con un error del tipo `AbortError`, por lo que es posible responder a esto utilizando un bloque `try..catch` por ejemplo:
59
59
60
60
```js run async
61
-
// abort in 1 second
61
+
// Se abortara en un segundo
62
62
let controller = new AbortController();
63
63
setTimeout(() => controller.abort(), 1000);
64
64
@@ -67,20 +67,20 @@ try {
67
67
signal: controller.signal
68
68
});
69
69
} catch(err) {
70
-
if (err.name == 'AbortError') { // handle abort()
70
+
if (err.name == 'AbortError') { // se maneja el abort()
71
71
alert("Aborted!");
72
72
} else {
73
73
throw err;
74
74
}
75
75
}
76
76
```
77
77
78
-
**`AbortController` is scalable, it allows to cancel multiple fetches at once.**
78
+
**`AbortController`es escalable, permitiendo cancelar múltiples fetch a la vez.**
79
79
80
-
For instance, here we fetch many `urls` in parallel, and the controller aborts them all:
80
+
Por ejemplo, aquí tenemos muchas `urls`en paralelo, y el controlador las aborta todas:
81
81
82
82
```js
83
-
let urls = [...]; // a list of urls to fetch in parallel
83
+
let urls = [...]; // una lista de urls para utilizar fetch en paralelo
// if controller.abort() is called from elsewhere,
94
-
// it aborts all fetches
93
+
// si controller.abort() es llamado,
94
+
// se abortaran todas las solicitudes fetch
95
95
```
96
96
97
-
If we have our own asynchronous jobs, different from `fetch`, we can use a single `AbortController` to stop those, together with fetches.
97
+
En el caso de tener nuestras propias tareas asincrónicas aparte de `fetch`, podemos utilizar un único `AbortController`para detenerlas junto con fetch.
98
98
99
-
We just need to listen to its `abort` event:
99
+
Solo es necesario escuchar el evento `abort`:
100
100
101
101
```js
102
102
let urls = [...];
103
103
let controller = new AbortController();
104
104
105
-
let ourJob = new Promise((resolve, reject) => { // our task
105
+
let ourJob = new Promise((resolve, reject) => { // nuestra tarea
let fetchJobs = urls.map(url => fetch(url, { // fetches
110
+
let fetchJobs = urls.map(url => fetch(url, { // varios fetch
111
111
signal: controller.signal
112
112
}));
113
113
114
-
// Wait for fetches and our task in parallel
114
+
// Se espera por la finalización de los fetch y nuestra tarea
115
115
let results = await Promise.all([...fetchJobs, ourJob]);
116
116
117
-
// if controller.abort() is called from elsewhere,
118
-
// it aborts all fetches and ourJob
117
+
// en caso de que se llame al método controller.abort() desde algún sitio,
118
+
// se abortan todos los fetch y nuestra tarea.
119
119
```
120
120
121
-
So `AbortController` is not only for `fetch`, it's a universal object to abort asynchronous tasks, and `fetch` has built-in integration with it.
121
+
Por lo tanto, si bien `fetch` incorpora esta funcionalidad de forma nativa, `AbortController` no es sólo para `fetch`, sino que es un objeto universal para abortar tareas asincrónicas.
0 commit comments