Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Promise API#313

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
joaquinelio merged 17 commits intojavascript-tutorial:masterfromjoaquinelio:papi
Aug 6, 2020
Merged
Changes fromall commits
Commits
Show all changes
17 commits
Select commitHold shift + click to select a range
2527cc9
Promise API
joaquinelioJul 22, 2020
e998eda
fix .race
joaquinelioJul 22, 2020
e223eaf
Update article.md
joaquinelioJul 31, 2020
6c720ef
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 5, 2020
d0e5b3b
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 5, 2020
cb8b653
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 5, 2020
dcdbb9a
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
36ef3db
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
99d842e
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
5974d39
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
ace75fe
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
8e7e076
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
40ea7fd
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
b1f5696
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
c899ba3
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
6090923
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
5956b2c
Update 1-js/11-async/05-promise-api/article.md
joaquinelioAug 6, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 67 additions & 67 deletions1-js/11-async/05-promise-api/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,40 @@
# Promise API

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

## Promise.all

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

For instance, download several URLsin parallel and process the content once they are all done.
Por ejemplo, descargar varias URLsen paralelo y procesar su contenido en cuanto todas ellas finalicen.

That's what`Promise.all` is for.
Para ello es`Promise.all`.

The syntax is:
La sintaxis es:

```js
let promise = Promise.all([...promises...]);
```

`Promise.all`takes an arrayof promises (it technically can be anyiterable, but is usually an array)and returns a new promise.
`Promise.all`toma un arrayde promesas (técnicamente puede ser cualquieriterable pero usualmente es un array)y devuelve una nueva promesa.

The new promise resolves when all listed promises are settled, and thearrayof their results becomes its result.
Esta nueva promesa es resuelta en cuanto todas las promesas listadas se resuelven y elarrayde aquellos resultados se vuelve su resultado.

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

```js run
Promise.all([
new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
new Promise(resolve => setTimeout(() => resolve(3), 1000)) // 3
]).then(alert); // 1,2,3when promises are ready: each promise contributes an array member
]).then(alert); // 1,2,3cuando las promesas están listas: cada promesa constituye un miembro del array
```

Please note that the order of the resultingarraymembers is the same as in its source promises. Even though the first promise takes the longest time to resolve, it's still first in thearrayof results.
Ten en cuenta que el orden de los miembros delarrayes 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 elarrayde resultados.

A common trick is to map anarrayof job data into anarrayof promises, and then wrap that into `Promise.all`.
Un truco común es mapear unarrayde datos de trabajo dentro de unarrayde promesas, y entonces envolverlos dentro de un `Promise.all`.

For instance, if we have anarrayof URLs,we canfetch them all like this:
Por ejemplo, si tenemos unarrayde URLs,podemos usar `fetch` en todos ellos así:

```js run
let urls = [
Expand All@@ -43,17 +43,17 @@ let urls = [
'https://api.github.com/users/jeresig'
];

//map every urlto the promise of the fetch
//"mapear" cada urla la promesa de su fetch
let requests = urls.map(url => fetch(url));

// Promise.allwaits until all jobs are resolved
// Promise.allespera hasta que todas la tareas estén resueltas
Promise.all(requests)
.then(responses => responses.forEach(
response => alert(`${response.url}: ${response.status}`)
));
```

A bigger example with fetching user information for anarrayof GitHub users by their names (we could fetch an arrayof goods by their ids, the logic is identical):
Un mayor ejemplo con fetch: la búsqueda de información de usuario para unarrayde usuarios de GitHub por sus nombres (o podríamos buscar un arrayde bienes por sus "id", la lógica es idéntica):

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

Promise.all(requests)
.then(responses => {
//all responses are resolved successfully
//todas las respuestas son resueltas satisfactoriamente
for(let response of responses) {
alert(`${response.url}: ${response.status}`); //shows 200for every url
alert(`${response.url}: ${response.status}`); //muestra 200por cada url
}

return responses;
})
//maparrayof responses into anarrayof response.json()to read their content
//mapea elarrayde resultados dentro de unarrayde response.json()para leer sus contenidos
.then(responses => Promise.all(responses.map(r => r.json())))
//all JSON answers are parsed: "users"is the arrayof them
//todas las respuestas JSON son analizadas: "users"es el arrayde ellas
.then(users => users.forEach(user => alert(user.name)));
```

**If any of the promises is rejected, the promise returned by `Promise.all`immediately rejects with that error.**
**Si cualquiera de las promesas es rechazada, la promesa devuelta por `Promise.all`inmediatamente rechaza: "reject" con ese error.**

For instance:
Por ejemplo:

```js run
Promise.all([
Expand All@@ -89,20 +89,20 @@ Promise.all([
]).catch(alert); // Error: Whoops!
```

Here the second promise rejects in two seconds. That leads to an immediate rejection of `Promise.all`,so `.catch`executes: the rejectionerrorbecomes the outcome of the entire`Promise.all`.
Aquí la segunda promesa se rechaza en dos segundos. Esto lleva a un rechazo inmediato de `Promise.all`,entonces `.catch`se ejecuta: elerrordel rechazo se vuelve la salida del`Promise.all` entero.

```warn header="In case of anerror,other promises are ignored"
If one promise rejects, `Promise.all`immediately rejects, completely forgetting about the other ones in the list. Their results are ignored.
```warn header="En caso deerror,las demás promesas son ignoradas"
Si una promesa se rechaza, `Promise.all`se rechaza inmediatamente, olvidando completamente las otras de la lista. Aquellos resultados son ignorados.

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

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

````smart header="`Promise.all(iterable)`allows non-promise \"regular\"values in`iterable`"
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 resultingarray"as is".
````smart header="`Promise.all(iterable)`permite valores \"comunes\"que no sean promesas en`iterable`"
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 alarrayresultante "tal como está".

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

```js run
Promise.all([
Expand All@@ -114,31 +114,31 @@ Promise.all([
]).then(alert); // 1, 2, 3
```

So we are able to pass ready values to`Promise.all`where convenient.
Entonces podemos pasar valores listos a`Promise.all`donde sea conveniente.
````

## Promise.allSettled

[recent browser="new"]

`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:
`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:

```js
Promise.all([
fetch('/template.html'),
fetch('/style.css'),
fetch('/data.json')
]).then(render); // rendermethod needs results of all fetches
]).then(render); //el métodorendernecesita los resultados de todos los fetch
```

`Promise.allSettled`just waits for all promises to settle, regardless of the result. The resultingarrayhas:
`Promise.allSettled`solo espera que todas las promesas se resuelvan sin importar sus resultados. Elarrayresultante tiene:

- `{status:"fulfilled", value:result}`for successful responses,
- `{status:"rejected", reason:error}`for errors.
- `{status:"fulfilled", value:result}`para respuestas exitosas,
- `{status:"rejected", reason:error}`para errores.

For example, we'd like tofetch the information about multiple users. Even if one request fails, we're still interested in the others.
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.

Let's use `Promise.allSettled`:
Usemos `Promise.allSettled`:

```js run
let urls = [
Expand All@@ -160,7 +160,7 @@ Promise.allSettled(urls.map(url => fetch(url)))
});
```

The `results`in the line `(*)`above will be:
El `results`de la línea `(*)`de arriba será:
```js
[
{status: 'fulfilled', value: ...response...},
Expand All@@ -169,11 +169,11 @@ The `results` in the line `(*)` above will be:
]
```

So for each promise we get its status and `value/error`.
Entonces para cada promesa obtendremos su estado y `value/error`.

### Polyfill

If the browserdoesn't support `Promise.allSettled`,it's easy to polyfill:
Si el browserno soporta `Promise.allSettled`,es fácil implementarlo:

```js
if(!Promise.allSettled) {
Expand All@@ -189,23 +189,23 @@ if(!Promise.allSettled) {
}
```

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

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

Now we can use`Promise.allSettled`to get the results of *all* given promises, even if some of them reject.
Ahora podemos usar`Promise.allSettled`para obtener el resultado de *todas* las promesas dadas incluso si algunas son rechazadas.

## Promise.race

Similarto `Promise.all`, but waits only for the first settled promise and gets its result (or error).
Similara `Promise.all` pero espera solamente por la primera respuesta y obtiene su resultado (o error).

The syntax is:
Su sintaxis es:

```js
let promise = Promise.race(iterable);
```

For instance, here the result will be `1`:
Por ejemplo, aquí el resultado será `1`:

```js run
Promise.race([
Expand All@@ -215,28 +215,28 @@ Promise.race([
]).then(alert); // 1
```

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


## Promise.resolve/reject

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

We cover them here for completeness and for those who can't use`async/await` for some reason.
Las tratamos aquí para completar la cobertura y por aquellos casos que por algún motivo no puedan usar`async/await`.

### Promise.resolve

`Promise.resolve(value)`creates a resolved promise with the result `value`.
`Promise.resolve(value)`crea una promesa resuelta con el resultado `value`.

Same as:
Tal como:

```js
let promise = new Promise(resolve => resolve(value));
```

The method is used for compatibility, when a function is expected to return a promise.
El método es usado por compatibilidad, cuando se espera que una función devuelva una promesa.

For example, the`loadCached`function below fetches aURLand remembers (caches) its content. For future calls with the sameURLit 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:
Por ejemplo, la función`loadCached`abajo busca unaURLy recuerda (en caché) su contenido. Futuros llamados con la mismaURLdevolverá el contenido de caché, pero usa `Promise.resolve`para hacer una promesa de él y así el valor devuelto es siempre una promesa:

```js
let cache = new Map();
Expand All@@ -257,30 +257,30 @@ function loadCached(url) {
}
```

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 `(*)`.
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 `(*)`.

### Promise.reject

`Promise.reject(error)`creates a rejected promise with `error`.
`Promise.reject(error)`crea una promesa rechazada con `error`.

Same as:
Tal como:

```js
let promise = new Promise((resolve, reject) => reject(error));
```

In practice, this method is almost never used.
En la práctica este método casi nunca es usado.

##Summary
##Resumen

There are 5 static methods of`Promise` class:
Existen 5 métodos estáticos de la clase`Promise`:

1. `Promise.all(promises)` --waits for all promises to resolve and returns anarrayof their results. If any of the given promises rejects, it becomes theerrorof `Promise.all`, and all other results are ignored.
2. `Promise.allSettled(promises)` (recently added method) --waits for all promises to settle and returns their results as an arrayof objects with:
- `status`: `"fulfilled"`or `"rejected"`
- `value` (if fulfilled)or `reason` (if rejected).
3. `Promise.race(promises)` --waits for the first promise to settle, and its result/errorbecomes the outcome.
4. `Promise.resolve(value)` --makes a resolved promise with the givenvalue.
5. `Promise.reject(error)` --makes a rejected promise with the givenerror.
1. `Promise.all(promises)` --espera que todas las promesas se resuelvan y devuelve unarrayde sus resultados. Si cualquiera es rechazada se vuelve elerrorde `Promise.all` y los demás resultados son ignorados.
2. `Promise.allSettled(promises)` (método recientemente añadido) --espera que toda las promesas respondan y devuelve sus resultados como un arrayde objetos con:
- `status`: `"fulfilled"`o `"rejected"`
- `value` (si fulfilled)o `reason` (si rejected).
3. `Promise.race(promises)` --espera a la primera promesa que responda y aquel resultado oerrorse vuelve su resultado o error.
4. `Promise.resolve(value)` --crea una promesa resuelta con el "value" dado.
5. `Promise.reject(error)` --crea una promesa rechazada con el "error" dado.

Of these five, `Promise.all`is probably the most common in practice.
De las 5, `Promise.all`es probablemente la más común en la práctica.

[8]ページ先頭

©2009-2025 Movatter.jp