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
]).then(alert); // 1,2,3 when promises are ready: each promise contributes an array member
30
+
]).then(alert); // 1,2,3 cuando las promesas están listas: cada promesa constituye un miembro del array
31
31
```
32
32
33
-
Please note that the order of the resulting array members is the same as in its source promises. Even though the first promise takes the longest time to resolve, it's still first in the array of results.
33
+
Ten en cuenta que el orden de los miembros del array es el mismo que el de las promesas que los originan. Aunque la primera promesa es la que toma más tiempo en resolverse, es aún la primera en el array de resultados.
34
34
35
-
A common trick is to map an array of job data into an array of promises, and then wrap that into`Promise.all`.
35
+
Un truco común es mapear un array de datos de trabajo dentro de un array de promesas, y entonces envolverlos dentro de un`Promise.all`.
36
36
37
-
For instance, if we have an array of URLs, we can fetch them all like this:
37
+
Por ejemplo, si tenemos un array de URLs, podemos usar `fetch` en todos ellos así:
38
38
39
39
```js run
40
40
let urls = [
@@ -43,17 +43,17 @@ let urls = [
43
43
'https://api.github.com/users/jeresig'
44
44
];
45
45
46
-
//map every url to the promise of the fetch
46
+
//"mapear" cada url a la promesa de su fetch
47
47
let requests =urls.map(url=>fetch(url));
48
48
49
-
// Promise.all waits until all jobs are resolved
49
+
// Promise.all espera hasta que todas la tareas estén resueltas
A bigger example with fetching user information for an array of GitHub users by their names (we could fetch an array of goods by their ids, the logic is identical):
56
+
Un mayor ejemplo con fetch: la búsqueda de información de usuario para un array de usuarios de GitHub por sus nombres (o podríamos buscar un array de bienes por sus "id", la lógica es idéntica):
57
57
58
58
```js run
59
59
let names = ['iliakan', 'remy', 'jeresig'];
@@ -62,22 +62,22 @@ let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));
62
62
63
63
Promise.all(requests)
64
64
.then(responses=> {
65
-
//all responses are resolved successfully
65
+
//todas las respuestas son resueltas satisfactoriamente
66
66
for(let response of responses) {
67
-
alert(`${response.url}: ${response.status}`); //shows 200 for every url
67
+
alert(`${response.url}: ${response.status}`); //muestra 200 por cada url
68
68
}
69
69
70
70
return responses;
71
71
})
72
-
//map array of responses into an array of response.json() to read their content
72
+
//mapea el array de resultados dentro de un array de response.json() para leer sus contenidos
**If any of the promises is rejected, the promise returned by`Promise.all`immediately rejects with that error.**
78
+
**Si cualquiera de las promesas es rechazada, la promesa devuelta por`Promise.all`inmediatamente rechaza: "reject" con ese error.**
79
79
80
-
For instance:
80
+
Por ejemplo:
81
81
82
82
```js run
83
83
Promise.all([
@@ -89,20 +89,20 @@ Promise.all([
89
89
]).catch(alert); // Error: Whoops!
90
90
```
91
91
92
-
Here the second promise rejects in two seconds. That leads to an immediate rejection of`Promise.all`, so`.catch`executes: the rejection error becomes the outcome of the entire `Promise.all`.
92
+
Aquí la segunda promesa se rechaza en dos segundos. Esto lleva a un rechazo inmediato de`Promise.all`, entonces`.catch`se ejecuta: el error del rechazo se vuelve la salida del `Promise.all` entero.
93
93
94
-
```warn header="In case of an error, other promises are ignored"
95
-
If one promise rejects, `Promise.all` immediately rejects, completely forgetting about the other ones in the list. Their results are ignored.
94
+
```warn header="En caso de error, las demás promesas son ignoradas"
95
+
Si una promesa se rechaza, `Promise.all` se rechaza inmediatamente, olvidando completamente las otras de la lista. Aquellos resultados son ignorados.
96
96
97
-
For example, if there are multiple `fetch` calls, like in the example above, and one fails, the others will still continue to execute, but `Promise.all` won't watch them anymore. They will probably settle, but their results will be ignored.
97
+
Por ejemplo, si hay múltiples llamados `fetch`, como en el ejemplo arriba, y uno falla, los demás aún continuarán en ejecución, pero `Promise.all` no las observará más. Ellas probablemente respondan pero sus resultados serán ignorados.
98
98
99
-
`Promise.all` does nothing to cancel them, as there's no concept of "cancellation" in promises. In [another chapter](info:fetch-abort) we'll cover `AbortController` that can help with that, but it's not a part of the Promise API.
99
+
`Promise.all` no hace nada para cancelarlas, no existe un concepto de "cancelación" en las promesas. En [otro capítulo](info:fetch-abort) veremos `AbortController` que puede ayudar con ello pero no es parte de la API de las promesas.
100
100
```
101
101
102
-
````smart header="`Promise.all(iterable)`allows non-promise\"regular\"values in `iterable`"
103
-
Normally, `Promise.all(...)`accepts an iterable (in most cases an array) of promises. But if any of those objects is not a promise, it's passed to the resulting array "as is".
102
+
````smart header="`Promise.all(iterable)`permite valores\"comunes\"que no sean promesas en `iterable`"
103
+
Normalmente, `Promise.all(...)`acepta un iterable (array en la mayoría de los casos) de promesas. Pero si alguno de esos objetos no es una promesa, es pasado al array resultante "tal como está".
104
104
105
-
For instance, here the results are`[1, 2, 3]`:
105
+
Por ejemplo, aquí los resultados son`[1, 2, 3]`:
106
106
107
107
```js run
108
108
Promise.all([
@@ -114,31 +114,31 @@ Promise.all([
114
114
]).then(alert); // 1, 2, 3
115
115
```
116
116
117
-
So we are able to pass ready values to `Promise.all`where convenient.
117
+
Entonces podemos pasar valores listos a `Promise.all`donde sea conveniente.
118
118
````
119
119
120
120
## Promise.allSettled
121
121
122
122
[recent browser="new"]
123
123
124
-
`Promise.all` rejects as a whole if any promise rejects. That's good for "all or nothing" cases, when we need *all* results successful to proceed:
124
+
`Promise.all` rechaza como un todo si cualquiera de sus promesas es rechazada. Esto es bueno para los casos de "todo o nada", cuando necesitamos que *todos* los resultados sean exitosos para proceder:
125
125
126
126
```js
127
127
Promise.all([
128
128
fetch('/template.html'),
129
129
fetch('/style.css'),
130
130
fetch('/data.json')
131
-
]).then(render); // render method needs results of all fetches
131
+
]).then(render); // el método render necesita los resultados de todos los fetch
132
132
```
133
133
134
-
`Promise.allSettled` just waits for all promises to settle, regardless of the result. The resulting array has:
134
+
`Promise.allSettled` solo espera que todas las promesas se resuelvan sin importar sus resultados. El array resultante tiene:
135
135
136
-
- `{status:"fulfilled", value:result}` for successful responses,
137
-
- `{status:"rejected", reason:error}` for errors.
136
+
- `{status:"fulfilled", value:result}` para respuestas exitosas,
137
+
- `{status:"rejected", reason:error}` para errores.
138
138
139
-
For example, we'd like to fetch the information about multiple users. Even if one request fails, we're still interested in the others.
139
+
Por ejemplo, quisiéramos hacer "fetch" de la información de múltiples usuarios. Incluso si uno falla, aún estaremos interesados en los otros.
@@ -169,11 +169,11 @@ The `results` in the line `(*)` above will be:
169
169
]
170
170
```
171
171
172
-
So for each promise we get its status and `value/error`.
172
+
Entonces para cada promesa obtendremos su estado y `value/error`.
173
173
174
174
### Polyfill
175
175
176
-
If the browser doesn't support `Promise.allSettled`, it's easy to polyfill:
176
+
Si el browser no soporta `Promise.allSettled`, es fácil implementarlo:
177
177
178
178
```js
179
179
if(!Promise.allSettled) {
@@ -189,23 +189,23 @@ if(!Promise.allSettled) {
189
189
}
190
190
```
191
191
192
-
In this code, `promises.map` takes input values, turns them into promises (just in case a non-promise was passed) with `p => Promise.resolve(p)`, and then adds `.then` handler to every one.
192
+
En este código, `promises.map` toma los valores de entrada, los transforma en promesas (por si no lo eran) con `p => Promise.resolve(p)`, entonces agrega un manejador `.then` a cada una.
193
193
194
-
That handler turns a successful result `value` into `{status:'fulfilled', value}`, and an error `reason` into `{status:'rejected', reason}`. That's exactly the format of `Promise.allSettled`.
194
+
Este manejador ("handler") transforma un resultado extitoso `value` en `{status:'fulfilled', value}`, y un error `reason` en `{status:'rejected', reason}`. Ese es exactamente el formato de `Promise.allSettled`.
195
195
196
-
Now we can use `Promise.allSettled` to get the results of *all* given promises, even if some of them reject.
196
+
Ahora podemos usar `Promise.allSettled` para obtener el resultado de *todas* las promesas dadas incluso si algunas son rechazadas.
197
197
198
198
## Promise.race
199
199
200
-
Similar to `Promise.all`, but waits only for the first settled promise and gets its result (or error).
200
+
Similar a `Promise.all` pero espera solamente por la primera respuesta y obtiene su resultado (o error).
201
201
202
-
The syntax is:
202
+
Su sintaxis es:
203
203
204
204
```js
205
205
let promise = Promise.race(iterable);
206
206
```
207
207
208
-
For instance, here the result will be `1`:
208
+
Por ejemplo, aquí el resultado será `1`:
209
209
210
210
```js run
211
211
Promise.race([
@@ -215,28 +215,28 @@ Promise.race([
215
215
]).then(alert); // 1
216
216
```
217
217
218
-
The first promise here was fastest, so it became the result. After the first settled promise "wins the race", all further results/errors are ignored.
218
+
La primera promesa fue la más rápida, por lo que se vuelve resultado. En cuanto una promesa responde, "gana la carrera", y todos los resultados o errores posteriores son ignorados.
219
219
220
220
221
221
## Promise.resolve/reject
222
222
223
-
Methods `Promise.resolve` and `Promise.reject` are rarely needed in modern code, because `async/await` syntax (we'll cover it [a bit later](info:async-await)) makes them somewhat obsolete.
223
+
Los métodos `Promise.resolve` y `Promise.reject` son raramente necesitados en código moderno porque la sintaxis `async/await` (que veremos [luego](info:async-await)) las hace algo obsoletas.
224
224
225
-
We cover them here for completeness and for those who can't use `async/await` for some reason.
225
+
Las tratamos aquí para completar la cobertura y por aquellos casos que por algún motivo no puedan usar `async/await`.
226
226
227
227
### Promise.resolve
228
228
229
-
`Promise.resolve(value)` creates a resolved promise with the result `value`.
229
+
`Promise.resolve(value)` crea una promesa resuelta con el resultado `value`.
230
230
231
-
Same as:
231
+
Tal como:
232
232
233
233
```js
234
234
let promise = new Promise(resolve => resolve(value));
235
235
```
236
236
237
-
The method is used for compatibility, when a function is expected to return a promise.
237
+
El método es usado por compatibilidad, cuando se espera que una función devuelva una promesa.
238
238
239
-
For example, the `loadCached` function below fetches a URL and remembers (caches) its content. For future calls with the same URL it immediately gets the previous content from cache, but uses `Promise.resolve` to make a promise of it, so the returned value is always a promise:
239
+
Por ejemplo, la función `loadCached` abajo busca una URL y recuerda (en caché) su contenido. Futuros llamados con la misma URL devolverá el contenido de caché, pero usa `Promise.resolve` para hacer una promesa de él y así el valor devuelto es siempre una promesa:
240
240
241
241
```js
242
242
let cache = new Map();
@@ -257,30 +257,30 @@ function loadCached(url) {
257
257
}
258
258
```
259
259
260
-
We can write `loadCached(url).then(…)`, because the function is guaranteed to return a promise. We can always use `.then` after `loadCached`. That's the purpose of `Promise.resolve` in the line `(*)`.
260
+
Podemos escribir `loadCached(url).then(…)` porque se garantiza que la función devuelve una promesa. Siempre podremos usar `.then` después de `loadCached`. Ese es el propósito de `Promise.resolve` en la línea `(*)`.
261
261
262
262
### Promise.reject
263
263
264
-
`Promise.reject(error)` creates a rejected promise with `error`.
264
+
`Promise.reject(error)` crea una promesa rechazada con `error`.
265
265
266
-
Same as:
266
+
Tal como:
267
267
268
268
```js
269
269
let promise = new Promise((resolve, reject) => reject(error));
270
270
```
271
271
272
-
In practice, this method is almost never used.
272
+
En la práctica este método casi nunca es usado.
273
273
274
-
## Summary
274
+
## Resumen
275
275
276
-
There are 5 static methods of `Promise` class:
276
+
Existen 5 métodos estáticos de la clase `Promise`:
277
277
278
-
1. `Promise.all(promises)` -- waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, it becomes the error of `Promise.all`, and all other results are ignored.
279
-
2. `Promise.allSettled(promises)` (recently added method) -- waits for all promises to settle and returns their results as an array of objects with:
280
-
- `status`: `"fulfilled"` or `"rejected"`
281
-
- `value` (if fulfilled) or `reason` (if rejected).
282
-
3. `Promise.race(promises)` -- waits for the first promise to settle, and its result/error becomes the outcome.
283
-
4. `Promise.resolve(value)` -- makes a resolved promise with the given value.
284
-
5. `Promise.reject(error)` -- makes a rejected promise with the given error.
278
+
1. `Promise.all(promises)` -- espera que todas las promesas se resuelvan y devuelve un array de sus resultados. Si cualquiera es rechazada se vuelve el error de `Promise.all` y los demás resultados son ignorados.
279
+
2. `Promise.allSettled(promises)` (método recientemente añadido) -- espera que toda las promesas respondan y devuelve sus resultados como un array de objetos con:
280
+
- `status`: `"fulfilled"` o `"rejected"`
281
+
- `value` (si fulfilled) o `reason` (si rejected).
282
+
3. `Promise.race(promises)` -- espera a la primera promesa que responda y aquel resultado o error se vuelve su resultado o error.
283
+
4. `Promise.resolve(value)` -- crea una promesa resuelta con el "value" dado.
284
+
5. `Promise.reject(error)` -- crea una promesa rechazada con el "error" dado.
285
285
286
-
Of these five, `Promise.all` is probably the most common in practice.
286
+
De las 5, `Promise.all` es probablemente la más común en la práctica.
0 commit comments