Skip to content

Commit 846f944

Browse files
authored
Merge pull request #360 from MaskeZen/fetch-abort
Fetch: Abort
2 parents b364a89 + 86fafcf commit 846f944

File tree

1 file changed

+31
-31
lines changed

1 file changed

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

22
# Fetch: Abort
33

4-
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`?
55

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.
77

8-
The usage is pretty simple:
8+
Su uso es muy sencillo:
99

10-
- Step 1: create a controller:
10+
- Paso 1: crear un controlador:
1111

1212
```js
1313
let controller = new AbortController();
1414
```
1515

16-
A controller is an extremely simple object.
16+
Este controlador es un objeto extremadamente simple.
1717

18-
- It has a single method `abort()`, and a single property `signal`.
19-
- When `abort()` is called:
20-
- `abort` event triggers on `controller.signal`
21-
- `controller.signal.aborted` property becomes `true`.
18+
- Tiene un único método `abort()`, así como una única propiedad `signal`.
19+
- Cuando `abort()` es invocado:
20+
- El evento `abort` se dispara en `controller.signal`
21+
- La propiedad `controller.signal.aborted` toma el valor `true`.
2222

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`.
2424

25-
Like this (without `fetch` yet):
25+
Tal como se muestra a continuación (por ahora sin `fetch`):
2626

2727
```js run
2828
let controller = new AbortController();
@@ -36,7 +36,7 @@ The usage is pretty simple:
3636
alert(signal.aborted); // true
3737
```
3838

39-
- Step 2: pass the `signal` property to `fetch` option:
39+
- Paso 2: Se pasa la propiedad `signal` en la opción de `fetch`:
4040

4141
```js
4242
let controller = new AbortController();
@@ -45,20 +45,20 @@ The usage is pretty simple:
4545
});
4646
```
4747

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`.
4949

50-
- Step 3: to abort, call `controller.abort()`:
50+
- Paso 3: Se llama al método `controller.abort()` para abortar:
5151

5252
```js
5353
controller.abort();
5454
```
5555

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.
5757

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:
5959

6060
```js run async
61-
// abort in 1 second
61+
// Se abortara en un segundo
6262
let controller = new AbortController();
6363
setTimeout(() => controller.abort(), 1000);
6464
@@ -67,20 +67,20 @@ try {
6767
signal: controller.signal
6868
});
6969
} catch(err) {
70-
if (err.name == 'AbortError') { // handle abort()
70+
if (err.name == 'AbortError') { // se maneja el abort()
7171
alert("Aborted!");
7272
} else {
7373
throw err;
7474
}
7575
}
7676
```
7777

78-
**`AbortController` is scalable, it allows to cancel multiple fetches at once.**
78+
**`AbortController` es escalable, permitiendo cancelar múltiples fetch a la vez.**
7979

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:
8181

8282
```js
83-
let urls = [...]; // a list of urls to fetch in parallel
83+
let urls = [...]; // una lista de urls para utilizar fetch en paralelo
8484
8585
let controller = new AbortController();
8686
@@ -90,32 +90,32 @@ let fetchJobs = urls.map(url => fetch(url, {
9090
9191
let results = await Promise.all(fetchJobs);
9292
93-
// 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
9595
```
9696

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.
9898

99-
We just need to listen to its `abort` event:
99+
Solo es necesario escuchar el evento `abort`:
100100

101101
```js
102102
let urls = [...];
103103
let controller = new AbortController();
104104
105-
let ourJob = new Promise((resolve, reject) => { // our task
105+
let ourJob = new Promise((resolve, reject) => { // nuestra tarea
106106
...
107107
controller.signal.addEventListener('abort', reject);
108108
});
109109
110-
let fetchJobs = urls.map(url => fetch(url, { // fetches
110+
let fetchJobs = urls.map(url => fetch(url, { // varios fetch
111111
signal: controller.signal
112112
}));
113113
114-
// Wait for fetches and our task in parallel
114+
// Se espera por la finalización de los fetch y nuestra tarea
115115
let results = await Promise.all([...fetchJobs, ourJob]);
116116
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.
119119
```
120120

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

Comments
 (0)