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

Async/await#317

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
vplentinax merged 8 commits intojavascript-tutorial:masterfromjoaquinelio:asyawa
Jul 31, 2020
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
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
14 changes: 7 additions & 7 deletions1-js/11-async/08-async-await/01-rewrite-async/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@

The notes are below the code:
Las notas están bajo el código:

```js run
async function loadJson(url) { // (1)
Expand All@@ -17,17 +17,17 @@ loadJson('no-such-user.json')
.catch(alert); // Error: 404 (4)
```

Notes:
Notas:

1.The function `loadJson`becomes `async`.
2.All`.then`inside are replaced with `await`.
3.We can `return response.json()`instead of awaiting for it, like this:
1.La función `loadJson`se vuelve `async`.
2.Todo lo que está dentro de`.then`es reemplazado por `await`.
3.Podemos devolver `return response.json()`en lugar de esperar por él, como esto:

```js
if (response.status == 200) {
return response.json(); // (3)
}
```

Then the outer code would have to `await` for that promise to resolve. In our case it doesn't matter.
4.The errorthrown from `loadJson`is handled by `.catch`.We can't use `await loadJson(…)`there, because we're not in an`async` function.
Entonces el código externo tendría que esperar que la promesa se resuelva. En nuestro caso eso no importa.
4.El errorarrojado por `loadJson`es manejado por `.catch`.No podemos usar `await loadJson(…)`allí, porque no estamos en una función`async`.
4 changes: 2 additions & 2 deletions1-js/11-async/08-async-await/01-rewrite-async/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@

#Rewrite using async/await
#Rescribir usando async/await

Rewrite this example code from the chapter <info:promise-chaining>using `async/await`instead of `.then/catch`:
Rescribir este código de ejemplo del capítulo <info:promise-chaining>usando `async/await`en vez de `.then/catch`:

```js run
function loadJson(url) {
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@

There are no tricks here. Just replace `.catch`with `try...catch`inside`demoGithubUser`and add `async/await`where needed:
No hay trampas aquí. Simplemente reemplaza `.catch`con `try...catch`dentro de`demoGithubUser`y agregar `async/await`donde sea necesario:

```js run
class HttpError extends Error {
Expand All@@ -24,15 +24,15 @@ async function demoGithubUser() {

let user;
while(true) {
let name = prompt("Enter a name?", "iliakan");
let name = prompt("Ingrese un nombre:", "iliakan");

try {
user = await loadJson(`https://api.github.com/users/${name}`);
break; // no error, exit loop
} catch(err) {
if (err instanceof HttpError && err.response.status == 404) {
// loop continues after the alert
alert("Nosuch user, please reenter.");
alert("Noexiste tal usuario, por favor reingrese.");
} else {
// unknown error, rethrow
throw err;
Expand All@@ -41,7 +41,7 @@ async function demoGithubUser() {
}


alert(`Full name: ${user.name}.`);
alert(`Nombre completo: ${user.name}.`);
return user;
}

Expand Down
14 changes: 7 additions & 7 deletions1-js/11-async/08-async-await/02-rewrite-async-2/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@

#Rewrite "rethrow"with async/await
#Reescribir "rethrow"con async/await

Below you can find the "rethrow"example from the chapter<info:promise-chaining>.Rewrite it using`async/await`instead of `.then/catch`.
Debajo puedes encontrar el ejemplo "rethrow"del capítulo<info:promise-chaining>.Rescríbelo usando`async/await`en vez de `.then/catch`.

And get rid of the recursion in favour of a loop in`demoGithubUser`:with `async/await` that becomes easy to do.
Y deshazte de la recursión en favor de un bucle en`demoGithubUser`:con `async/await`, que se vuelve fácil de hacer.

```js run
class HttpError extends Error {
Expand All@@ -25,18 +25,18 @@ function loadJson(url) {
})
}

//Ask for a user name untilgithubreturns a valid user
//Pide nombres hasta quegithubdevuelve un usuario válido
function demoGithubUser() {
let name = prompt("Enter a name?", "iliakan");
let name = prompt("Ingrese un nombre:", "iliakan");

return loadJson(`https://api.github.com/users/${name}`)
.then(user => {
alert(`Full name: ${user.name}.`);
alert(`Nombre completo: ${user.name}.`);
return user;
})
.catch(err => {
if (err instanceof HttpError && err.response.status == 404) {
alert("Nosuch user, please reenter.");
alert("Noexiste tal usuario, por favor reingrese.");
return demoGithubUser();
} else {
throw err;
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@

That's the case when knowing how it works inside is helpful.
Este es el caso cuando saber cómo trabaja por dentro es útil.

Just treat`async`call as promise and attach `.then` to it:
Simplemente trata el llamado`async`como una promesa y añádele `.then`:
```js run
async function wait() {
await new Promise(resolve => setTimeout(resolve, 1000));
Expand All@@ -10,7 +10,7 @@ async function wait() {
}

function f() {
//shows 10after 1 second
//muestra 10después de 1 segundo
*!*
wait().then(result => alert(result));
*/!*
Expand Down
12 changes: 6 additions & 6 deletions1-js/11-async/08-async-await/03-async-from-regular/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@

#Call asyncfrom non-async
#Llamado asyncdesde un non-async

We have a "regular" function. How to call`async`from it and use its result?
Tenemos una función "regular". ¿Cómo llamar`async`desde ella y usar el resultado?

```js
async function wait() {
Expand All@@ -11,10 +11,10 @@ async function wait() {
}

function f() {
// ...what to write here?
//we need to callasync wait()and wait to get 10
//remember, we can't use "await"
//¿...qué escribir aquí?
//Necesitamos llamarasync wait()y esperar a obtener 10
//recuerda, no podemos usar "await"
}
```

P.S. The task is technically very simple,but the question is quite common for developers new to async/await.
P.D. La tarea es técnicamente muy simple,pero la pregunta es muy común en desarrolladores nuevos en async/await.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp