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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
As we know,`fetch`returns a promise. AndJavaScriptgenerally has no concept of "aborting" a promise. So how can we abort a `fetch`?
Como sabemos`fetch`devuelve una promesa, y generalmenteJavaScriptno tiene un concepto de "abortar" una promesa. Entonces, ¿cómo podemos abortar una llamada al método `fetch`?
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.
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.
The usage is pretty simple:
Su uso es muy sencillo:
-Step 1:create a controller:
-Paso 1:crear un controlador:
```js
let controller = new AbortController();
```
A controller is an extremely simple object.
Este controlador es un objeto extremadamente simple.
-It has a single method`abort()`,and a single property `signal`.
-Paso 2:Se pasa la propiedad`signal`en la opción de`fetch`:
```js
let controller = new AbortController();
Expand All
@@ -45,20 +45,20 @@ The usage is pretty simple:
});
```
The`fetch`method knows how to work with`AbortController`,it listens to `abort`on `signal`.
El método`fetch`conoce como funciona`AbortController`,el escucha por `abort`en `signal`.
-Step 3:to abort, call`controller.abort()`:
-Paso 3:Se llama al método`controller.abort()` para abortar:
```js
controller.abort();
```
We're done: `fetch`gets the event from `signal`and aborts the request.
Y así `fetch`obtiene el evento desde `signal`y aborta la solicitud.
When a fetchis aborted, its promise rejects with anerror `AbortError`,so we should handle it, e.g. in`try..catch`:
Cuando un fetches abortado su promesa es rechazada con unerrordel tipo`AbortError`,por lo que es posible responder a esto utilizando un bloque`try..catch` por ejemplo:
```js run async
//abort in 1 second
//Se abortara en un segundo
let controller = new AbortController();
setTimeout(() => controller.abort(), 1000);
Expand All
@@ -67,20 +67,20 @@ try {
signal: controller.signal
});
} catch(err) {
if (err.name == 'AbortError') { //handle abort()
if (err.name == 'AbortError') { //se maneja el abort()
alert("Aborted!");
} else {
throw err;
}
}
```
**`AbortController`is scalable, it allows to cancel multiple fetches at once.**
**`AbortController`es escalable, permitiendo cancelar múltiples fetch a la vez.**
For instance, here we fetch many`urls`in parallel, and the controller aborts them all:
Por ejemplo, aquí tenemos muchas`urls`en paralelo, y el controlador las aborta todas:
```js
let urls = [...]; //a list of urlstofetchin parallel
let urls = [...]; //una lista de urlspara utilizarfetchen paralelo
let fetchJobs = urls.map(url => fetch(url, { //fetches
let fetchJobs = urls.map(url => fetch(url, { //varios fetch
signal: controller.signal
}));
//Wait for fetches and our task in parallel
//Se espera por la finalización de los fetch y nuestra tarea
let results = await Promise.all([...fetchJobs, ourJob]);
//ifcontroller.abort()is called from elsewhere,
//it aborts all fetches and ourJob
//en caso de que se llame al métodocontroller.abort()desde algún sitio,
//se abortan todos los fetch y nuestra tarea.
```
So `AbortController` is not only for`fetch`, it's a universal object to abort asynchronous tasks, and`fetch` has built-in integration with it.
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.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.