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
The `fetch`method allows to track *download* progress.
4
+
El método `fetch`permite rastrear el progreso de *descarga*.
5
5
6
-
Please note: there's currently no way for `fetch`to track *upload* progress. For that purpose, please use [XMLHttpRequest](info:xmlhttprequest), we'll cover it later.
6
+
Ten en cuenta: actualmente no hay forma de que `fetch`rastree el progreso de *carga*. Para ese propósito, utiliza [XMLHttpRequest](info:xmlhttprequest), lo cubriremos más adelante.
7
7
8
-
To track download progress, we can use `response.body` property. It's`ReadableStream` -- a special object that provides body chunk-by-chunk, as it comes. Readable streams are described in the [Streams API](https://streams.spec.whatwg.org/#rs-class) specification.
8
+
Para rastrear el progreso de la descarga, podemos usar la propiedad `response.body`. Su`ReadableStream`, un objeto especial que proporciona el cuerpo fragmento a fragmento, tal como viene. Las transmisiones legibles se describen en la especificación de la [API de transmisiones](https://streams.spec.whatwg.org/#rs-class).
9
9
10
-
Unlike `response.text()`, `response.json()`and other methods, `response.body`gives full control over the reading process, and we can count how much is consumed at any moment.
10
+
A diferencia de `response.text()`, `response.json()`y otros métodos, `response.body`da control total sobre el proceso de lectura, y podemos contar cuánto se consume en cualquier momento.
11
11
12
-
Here's the sketch of code that reads the reponse from`response.body`:
12
+
Aquí está el bosquejo del código que lee la respuesta de`response.body`:
13
13
14
14
```js
15
-
//instead of response.json() and other methods
15
+
//en lugar de response.json() y otros métodos
16
16
constreader=response.body.getReader();
17
17
18
-
//infinite loop while the body is downloading
18
+
//bucle infinito mientras el cuerpo se descarga
19
19
while(true) {
20
-
// done is true for the last chunk
21
-
// value is Uint8Array of the chunk bytes
20
+
// done es true para el último fragmento
21
+
// value es Uint8Array de los bytes del fragmento
22
22
const {done, value} =awaitreader.read();
23
23
24
24
if (done) {
25
25
break;
26
26
}
27
27
28
-
console.log(`Received${value.length} bytes`)
28
+
console.log(`Recibí${value.length} bytes`)
29
29
}
30
30
```
31
31
32
-
The result of `await reader.read()`call is an object with two properties:
33
-
-**`done`** -- `true`when the reading is complete, otherwise`false`.
34
-
-**`value`** -- a typed array of bytes: `Uint8Array`.
32
+
El resultado de la llamada `await reader.read()`es un objeto con dos propiedades:
33
+
-**`done`** -- `true`cuando la lectura está completa, de lo contrario`false`.
34
+
-**`value`** -- una matriz de tipo bytes: `Uint8Array`.
35
35
36
36
```smart
37
-
Streams API also describes asynchronous iteration over `ReadableStream` with `for await..of` loop, but it's not yet widely supported (see [browser issues](https://github.com/whatwg/streams/issues/778#issuecomment-461341033)), so we use `while` loop.
37
+
La API de transmisiones también describe la iteración asincrónica sobre `ReadableStream` con el bucle `for await..of`, pero aún no es ampliamente compatible (consulta [problemas del navegador](https://github.com/whatwg/streams/issues/778#issuecomment-461341033)), por lo que usamos el bucle `while`.
38
38
```
39
39
40
-
We receive response chunks in the loop, until the loading finishes, that is: until `done`becomes`true`.
40
+
Recibimos fragmentos de respuesta en el bucle, hasta que finaliza la carga, es decir: hasta que `done`se convierte en`true`.
41
41
42
-
To log the progress, we just need for every received fragment `value`to add its length to the counter.
42
+
Para registrar el progreso, solo necesitamos que cada `value`de fragmento recibido agregue su longitud al contador.
43
43
44
-
Here's the full working example that gets the response and logs the progress in console, more explanations to follow:
44
+
Aquí está el ejemplo funcional completo que obtiene la respuesta y registra el progreso en la consola, seguido de su explicación:
45
45
46
46
```js run async
47
-
//Step 1: start the fetch and obtain a reader
48
-
let response =awaitfetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');
47
+
//Paso 1: iniciar la búsqueda y obtener un lector
48
+
let response =awaitfetch('https://api.github.com/repos/javascript-tutorial/es.javascript.info/commits?per_page=100');
//Step 4: concatenate chunks into single Uint8Array
71
+
//Paso 4: concatenar fragmentos en un solo Uint8Array
72
72
let chunksAll =newUint8Array(receivedLength); // (4.1)
73
73
let position =0;
74
74
for(let chunk of chunks) {
75
75
chunksAll.set(chunk, position); // (4.2)
76
76
position +=chunk.length;
77
77
}
78
78
79
-
//Step 5: decode into a string
79
+
//Paso 5: decodificar en un string
80
80
let result =newTextDecoder("utf-8").decode(chunksAll);
81
81
82
-
//We're done!
82
+
//¡Hemos terminado!
83
83
let commits =JSON.parse(result);
84
84
alert(commits[0].author.login);
85
85
```
86
86
87
-
Let's explain that step-by-step:
87
+
Expliquemos eso paso a paso:
88
88
89
-
1.We perform `fetch`as usual, but instead of calling `response.json()`, we obtain a stream reader`response.body.getReader()`.
89
+
1.Realizamos `fetch`como de costumbre, pero en lugar de llamar a `response.json()`, obtenemos un lector de transmisión`response.body.getReader()`.
90
90
91
-
Please note, we can't use both these methods to read the same response: either use a reader or a response method to get the result.
92
-
2.Prior to reading, we can figure out the full response length from the`Content-Length` header.
91
+
Ten en cuenta que no podemos usar ambos métodos para leer la misma respuesta: usa un lector o un método de respuesta para obtener el resultado.
92
+
2.Antes de leer, podemos averiguar la longitud completa de la respuesta del encabezado`Content-Length`.
93
93
94
-
It may be absent for cross-origin requests (see chapter <info:fetch-crossorigin>) and, well, technically a server doesn't have to set it. But usually it's at place.
95
-
3.Call `await reader.read()`until it's done.
94
+
Puede estar ausente para solicitudes cross-origin (consulta el capítulo <info:fetch-crossorigin>) y, bueno, técnicamente un servidor no tiene que configurarlo. Pero generalmente está en su lugar.
95
+
3.Llama a `await reader.read()`hasta que esté listo.
96
96
97
-
We gather response chunks in the array`chunks`. That's important, because after the response is consumed, we won't be able to "re-read" it using `response.json()`or another way (you can try, there'll be an error).
98
-
4.At the end, we have `chunks` -- an array of `Uint8Array` byte chunks. We need to join them into a single result. Unfortunately, there's no single method that concatenates those, so there's some code to do that:
99
-
1.We create `chunksAll = new Uint8Array(receivedLength)` -- a same-typed array with the combined length.
100
-
2.Then use `.set(chunk, position)`method to copy each `chunk`one after another in it.
101
-
5.We have the result in `chunksAll`. It's a byte array though, not a string.
97
+
Recopilamos fragmentos de respuesta en la matriz`chunks`. Eso es importante, porque después de consumir la respuesta, no podremos "releerla" usando `response.json()`u otra forma (puedes intentarlo, habrá un error).
98
+
4.Al final, tenemos `chunks` - una matriz de fragmentos de bytes `Uint8Array`. Necesitamos unirlos en un solo resultado. Desafortunadamente, no hay un método simple que los concatene, por lo que hay un código para hacerlo:
99
+
1.Creamos `chunksAll = new Uint8Array(selectedLength)` -- una matriz del mismo tipo con la longitud combinada.
100
+
2.Luego usa el método `.set(chunk, position)`para copiar cada `chunk`uno tras otro en él.
101
+
5.Tenemos el resultado en `chunksAll`. Sin embargo, es una matriz de bytes, no un string.
102
102
103
-
To create a string, we need to interpret these bytes. The built-in [TextDecoder](info:text-decoder)does exactly that. Then we can `JSON.parse` it, if necessary.
103
+
Para crear un string, necesitamos interpretar estos bytes. El [TextDecoder](info:text-decoder)nativo hace exactamente eso. Luego podemos usar el resultado en `JSON.parse`, si es necesario.
104
104
105
-
What if we need binary content instead of a string? That's even simpler. Replace steps 4 and 5 with a single line that creates a`Blob`from all chunks:
105
+
¿Qué pasa si necesitamos contenido binario en lugar de un string? Eso es aún más sencillo. Reemplaza los pasos 4 y 5 con una sola línea que crea un`Blob`de todos los fragmentos:
106
106
```js
107
107
let blob =newBlob(chunks);
108
108
```
109
109
110
-
At the end we have the result (as a string or a blob, whatever is convenient), and progress-tracking in the process.
110
+
Al final tenemos el resultado (como un string o un blob, lo que sea conveniente) y el seguimiento del progreso en el proceso.
111
111
112
-
Once again, please note, that's not for *upload* progress (no way now with `fetch`), only for *download* progress.
112
+
Una vez más, ten en cuenta que eso no es para el progreso de *carga* (hasta ahora eso no es posible con`fetch`), solo para el progreso de *descarga*.
0 commit comments