Skip to content

Commit 74278ee

Browse files
authored
Merge pull request #313 from joaquinelio/papi
Promise API
2 parents 62d4c63 + 5956b2c commit 74278ee

File tree

1 file changed

+67
-67
lines changed

1 file changed

+67
-67
lines changed
Lines changed: 67 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,40 @@
11
# Promise API
22

3-
There are 5 static methods in the `Promise` class. We'll quickly cover their use cases here.
3+
Hay 5 métodos estáticos en la clase `Promise`. Veremos sus casos de uso aquí.
44

55
## Promise.all
66

7-
Let's say we want many promises to execute in parallel and wait until all of them are ready.
7+
Digamos que queremos que muchas promesas se ejecuten en paralelo y esperar hasta que todas ellas estén listas.
88

9-
For instance, download several URLs in parallel and process the content once they are all done.
9+
Por ejemplo, descargar varias URLs en paralelo y procesar su contenido en cuanto todas ellas finalicen.
1010

11-
That's what `Promise.all` is for.
11+
Para ello es `Promise.all`.
1212

13-
The syntax is:
13+
La sintaxis es:
1414

1515
```js
1616
let promise = Promise.all([...promises...]);
1717
```
1818

19-
`Promise.all` takes an array of promises (it technically can be any iterable, but is usually an array) and returns a new promise.
19+
`Promise.all` toma un array de promesas (técnicamente puede ser cualquier iterable pero usualmente es un array) y devuelve una nueva promesa.
2020

21-
The new promise resolves when all listed promises are settled, and the array of their results becomes its result.
21+
Esta nueva promesa es resuelta en cuanto todas las promesas listadas se resuelven y el array de aquellos resultados se vuelve su resultado.
2222

23-
For instance, the `Promise.all` below settles after 3 seconds, and then its result is an array `[1, 2, 3]`:
23+
Por ejemplo, el `Promise.all` debajo se resuelve después de 3 segundos, y su resultado es un array `[1, 2, 3]`:
2424

2525
```js run
2626
Promise.all([
2727
new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
2828
new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
2929
new Promise(resolve => setTimeout(() => resolve(3), 1000)) // 3
30-
]).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
3131
```
3232

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

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

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í:
3838

3939
```js run
4040
let urls = [
@@ -43,17 +43,17 @@ let urls = [
4343
'https://api.github.com/users/jeresig'
4444
];
4545

46-
// map every url to the promise of the fetch
46+
// "mapear" cada url a la promesa de su fetch
4747
let requests = urls.map(url => fetch(url));
4848

49-
// Promise.all waits until all jobs are resolved
49+
// Promise.all espera hasta que todas la tareas estén resueltas
5050
Promise.all(requests)
5151
.then(responses => responses.forEach(
5252
response => alert(`${response.url}: ${response.status}`)
5353
));
5454
```
5555

56-
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):
5757

5858
```js run
5959
let names = ['iliakan', 'remy', 'jeresig'];
@@ -62,22 +62,22 @@ let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));
6262

6363
Promise.all(requests)
6464
.then(responses => {
65-
// all responses are resolved successfully
65+
// todas las respuestas son resueltas satisfactoriamente
6666
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
6868
}
6969

7070
return responses;
7171
})
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
7373
.then(responses => Promise.all(responses.map(r => r.json())))
74-
// all JSON answers are parsed: "users" is the array of them
74+
// todas las respuestas JSON son analizadas: "users" es el array de ellas
7575
.then(users => users.forEach(user => alert(user.name)));
7676
```
7777

78-
**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.**
7979

80-
For instance:
80+
Por ejemplo:
8181

8282
```js run
8383
Promise.all([
@@ -89,20 +89,20 @@ Promise.all([
8989
]).catch(alert); // Error: Whoops!
9090
```
9191

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

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.
9696
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.
9898
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.
100100
```
101101

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á".
104104

105-
For instance, here the results are `[1, 2, 3]`:
105+
Por ejemplo, aquí los resultados son `[1, 2, 3]`:
106106

107107
```js run
108108
Promise.all([
@@ -114,31 +114,31 @@ Promise.all([
114114
]).then(alert); // 1, 2, 3
115115
```
116116

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.
118118
````
119119
120120
## Promise.allSettled
121121
122122
[recent browser="new"]
123123
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:
125125
126126
```js
127127
Promise.all([
128128
fetch('/template.html'),
129129
fetch('/style.css'),
130130
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
132132
```
133133
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:
135135
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.
138138
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.
140140
141-
Let's use `Promise.allSettled`:
141+
Usemos `Promise.allSettled`:
142142
143143
```js run
144144
let urls = [
@@ -160,7 +160,7 @@ Promise.allSettled(urls.map(url => fetch(url)))
160160
});
161161
```
162162
163-
The `results` in the line `(*)` above will be:
163+
El `results` de la línea `(*)` de arriba será:
164164
```js
165165
[
166166
{status: 'fulfilled', value: ...response...},
@@ -169,11 +169,11 @@ The `results` in the line `(*)` above will be:
169169
]
170170
```
171171
172-
So for each promise we get its status and `value/error`.
172+
Entonces para cada promesa obtendremos su estado y `value/error`.
173173
174174
### Polyfill
175175
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:
177177
178178
```js
179179
if(!Promise.allSettled) {
@@ -189,23 +189,23 @@ if(!Promise.allSettled) {
189189
}
190190
```
191191
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.
193193
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`.
195195
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.
197197
198198
## Promise.race
199199
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).
201201
202-
The syntax is:
202+
Su sintaxis es:
203203
204204
```js
205205
let promise = Promise.race(iterable);
206206
```
207207
208-
For instance, here the result will be `1`:
208+
Por ejemplo, aquí el resultado será `1`:
209209
210210
```js run
211211
Promise.race([
@@ -215,28 +215,28 @@ Promise.race([
215215
]).then(alert); // 1
216216
```
217217
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.
219219
220220
221221
## Promise.resolve/reject
222222
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.
224224
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`.
226226
227227
### Promise.resolve
228228
229-
`Promise.resolve(value)` creates a resolved promise with the result `value`.
229+
`Promise.resolve(value)` crea una promesa resuelta con el resultado `value`.
230230
231-
Same as:
231+
Tal como:
232232
233233
```js
234234
let promise = new Promise(resolve => resolve(value));
235235
```
236236
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.
238238
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:
240240
241241
```js
242242
let cache = new Map();
@@ -257,30 +257,30 @@ function loadCached(url) {
257257
}
258258
```
259259
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 `(*)`.
261261
262262
### Promise.reject
263263
264-
`Promise.reject(error)` creates a rejected promise with `error`.
264+
`Promise.reject(error)` crea una promesa rechazada con `error`.
265265
266-
Same as:
266+
Tal como:
267267
268268
```js
269269
let promise = new Promise((resolve, reject) => reject(error));
270270
```
271271
272-
In practice, this method is almost never used.
272+
En la práctica este método casi nunca es usado.
273273
274-
## Summary
274+
## Resumen
275275
276-
There are 5 static methods of `Promise` class:
276+
Existen 5 métodos estáticos de la clase `Promise`:
277277
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.
285285
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

Comments
 (0)