Repository navigation
Expand file tree
/
Copy pathindex.md
More file actions
121 lines (97 loc) · 3.26 KB
/
Copy pathindex.md
File metadata and controls
121 lines (97 loc) · 3.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
---
title: for await...of
slug: Web/JavaScript/Reference/Statements/for-await...of
---
{{jsSidebar("Statements")}}
La **sentencia** **`for await...of`** crea un bucle iterando tanto sobre objetos iterables asincrónicos como sincrónicos, incluyendo: built-in {{jsxref("String")}}, {{jsxref("Array")}}, objetos `Array`-like (por ej., {{jsxref("Functions/arguments", "arguments")}} o {{domxref("NodeList")}}), {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, y async/sync iterables definidos por el usuario. Invoca un hook de iteración personalizada con sentencias a ser ejecutadas por el valor de cada propiedad diferente del objeto.
## Sintaxis
```
for await (variable of iterable) {
sentencia
}
```
- `variable`
- : En cada iteración, el valor de una propiedad diferente es asignado a _variable_. _variable_ puede ser declarada con `const`, `let`, o `var`.
- `iterable`
- : Objeto sobre cuyas propiedades se itera.
### Iterando sobre iterables asincrónicos
También puedes iterar sobre un objeto que explícitamente implementa el protocolo async iterable:
```js
var asyncIterable = {
[Symbol.asyncIterator]() {
return {
i: 0,
next() {
if (this.i < 3) {
return Promise.resolve({ value: this.i++, done: false });
}
return Promise.resolve({ done: true });
},
};
},
};
(async function () {
for await (let num of asyncIterable) {
console.log(num);
}
})();
// 0
// 1
// 2
```
### Iterando sobre funciones generadoras asincrónicas
Debido a que las funciones generadoras asincrónicas implementan el protocolo async iterator, las mismas pueden ser iteradas utilizando `for await... of`
```js
async function* asyncGenerator() {
var i = 0;
while (i < 3) {
yield i++;
}
}
(async function () {
for await (let num of asyncGenerator()) {
console.log(num);
}
})();
// 0
// 1
// 2
```
Para un ejemplo más concreto de iteración sobre una función generadora utilizando `for await... of`, considera iterar sobre datos provistos por una API. Este ejemplo primero crea un iterador asincrónico para un stream de datos, luego lo utiliza para obtener el tamaño de la respuesta desde la API.
```js
async function* streamAsyncIterator(stream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
return;
}
yield value;
}
} finally {
reader.releaseLock();
}
}
// Obtiene datos desde url y calcula el tamaño de la respuesta utilizando la función generadora asincrónica.
async function getResponseSize(url) {
const response = await fetch(url);
// Almacenará el tamaño de la respuesta en bytes.
let responseSize = 0;
// El buble for-await-of. Itera asincrónicamente sobre cada parte de la respuesta.
for await (const chunk of streamAsyncIterator(response.body)) {
// Incrementando el tamaño total.
responseSize += chunk.length;
}
console.log(`Tamaño de la respuesta: ${responseSize} bytes`);
// salida esperada: "Tamaño de la respuesta: 1071472"
return responseSize;
}
getResponseSize("https://jsonplaceholder.typicode.com/photos");
```
## Especificaciones
{{Specifications}}
## Compatibilidad con navegadores
{{Compat}}
## Ver también
- {{jsxref("Statements/for...of")}}