Skip to content

Commit 35a4072

Browse files
committed
Translate 11-async/08-async-await
1 parent 448336a commit 35a4072

File tree

4 files changed

+79
-78
lines changed

4 files changed

+79
-78
lines changed

1-js/11-async/08-async-await/01-rewrite-async/solution.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
The notes are below the code:
2+
Le note sono sotto il codice:
33

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

20-
Notes:
20+
Note:
2121

22-
1. The function `loadJson` becomes `async`.
23-
2. All `.then` inside are replaced with `await`.
24-
3. We can `return response.json()` instead of awaiting for it, like this:
22+
1. La funzione `loadJson` diventa `async`.
23+
2. Tutti i `.then` interni sono sostituiti con `await`.
24+
3. Possiamo ritornare `response.json()` invece di aspettarlo (awaiting for it), come qui:
2525

2626
```js
2727
if (response.status == 200) {
2828
return response.json(); // (3)
2929
}
3030
```
3131

32-
Then the outer code would have to `await` for that promise to resolve. In our case it doesn't matter.
33-
4. The error thrown from `loadJson` is handled by `.catch`. We can't use `await loadJson(…)` there, because we're not in an `async` function.
32+
Poi il codice esterno avrebbe dovuto attendere (`await)` che la promise risolvesse. Nel nostro caso non è importante.
33+
4. L'errore sollevato da `loadJson` è gestito da `.catch`. Non possiamo usare `await loadJson(…)` qui, perchè non siamo in una funzione `async`.

1-js/11-async/08-async-await/02-rewrite-async-2/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11

2-
# Rewrite "rethrow" with async/await
2+
# Riscrivere "rethrow" con async/await
33

4-
Below you can find the "rethrow" example from the chapter <info:promise-chaining>. Rewrite it using `async/await` instead of `.then/catch`.
4+
Sotto puoi trovare l'esempio "rethrow" dal capitolo <info:promise-chaining>. Riscriverlo usando `async/await` invece di `.then/catch`.
55

6-
And get rid of the recursion in favour of a loop in `demoGithubUser`: with `async/await` that becomes easy to do.
6+
E sbarazzarsi della ricorsione a favore di un ciclo in `demoGithubUser`: con `async/await` diventa facile da fare.
77

88
```js run
99
class HttpError extends Error {
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
# Call async from non-async
33

4-
We have a "regular" function. How to call `async` from it and use its result?
4+
Abbiamo una funzione "regolare". How to call `async` da essa ed usare il suo risultato?
55

66
```js
77
async function wait() {
@@ -11,10 +11,10 @@ async function wait() {
1111
}
1212

1313
function f() {
14-
// ...what to write here?
15-
// we need to call async wait() and wait to get 10
16-
// remember, we can't use "await"
14+
// ...cosa bisonga scrivere qui?
15+
// dobbiamo chiamare async wait() ed aspettare per ricevere 10
16+
// ricorda, non possiamo usare "await"
1717
}
1818
```
1919

20-
P.S. The task is technically very simple, but the question is quite common for developers new to async/await.
20+
P.S. Il task è tecnicamente molto semplice, ma la domanda è piuttosto comune per gli sviluppatori nuovi ad async/await.
Lines changed: 64 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
# Async/await
22

3-
There's a special syntax to work with promises in a more comfortable fashion, called "async/await". It's surprisingly easy to understand and use.
3+
Esiste una sintassi speciale per lavorare con le promise in un modo più comodo, chiamata asnyc/await. È sorprendentemente facile da capire e usare.
4+
45

56
## Async functions
67

7-
Let's start with the `async` keyword. It can be placed before a function, like this:
8+
Iniziamo con la parola chiave `async`. Può essere messa prima di una funzione, come nell'esempio sotto:
89

910
```js
1011
async function f() {
1112
return 1;
1213
}
1314
```
1415

15-
The word "async" before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
16+
La parola "async" prima di una funzione significa una cosa semplice: la funzione ritorna sempre una promise. Gli altri valori sono "avvolti" wrapped in una promise risolta automaticamente.
1617

17-
For instance, this function returns a resolved promise with the result of `1`, let's test it:
18+
Per esempio, questa funzione ritorna una promise risolta con il risultato di `1`, proviamola:
1819

1920
```js run
2021
async function f() {
@@ -24,7 +25,7 @@ async function f() {
2425
f().then(alert); // 1
2526
```
2627

27-
...We could explicitly return a promise, that would be the same:
28+
...Possiamo anche ritornare esplicitamente una promise, sarebbe lo stesso:
2829

2930
```js run
3031
async function f() {
@@ -34,45 +35,45 @@ async function f() {
3435
f().then(alert); // 1
3536
```
3637

37-
So, `async` ensures that the function returns a promise, and wraps non-promises in it. Simple enough, right? But not only that. There's another keyword, `await`, that works only inside `async` functions, and it's pretty cool.
38+
Così, `async` assicura che la funzione ritorni una promise, e "avvolge" (wraps) le non-promise al suo interno. Abbastanza semplice, vero? Ma non sono quello. C'è un'altra parola chiave, `await`, che funziona solo nelle funzioni `async`, ed è piuttosto cool.
3839

3940
## Await
4041

41-
The syntax:
42+
La sintassi:
4243

4344
```js
44-
// works only inside async functions
45+
// funziona solo all'interno delle funzioni async
4546
let value = await promise;
4647
```
4748

48-
The keyword `await` makes JavaScript wait until that promise settles and returns its result.
49+
La parola chiave `await` fa attendere JavaScript fino a quando la promise è ferma (settles) e ritorna il suo risultato.
4950

50-
Here's an example with a promise that resolves in 1 second:
51+
Ecco un esempio con una promise che si risolve in un secondo:
5152
```js run
5253
async function f() {
5354

5455
let promise = new Promise((resolve, reject) => {
55-
setTimeout(() => resolve("done!"), 1000)
56+
setTimeout(() => resolve("fatto!"), 1000)
5657
});
5758

5859
*!*
59-
let result = await promise; // wait till the promise resolves (*)
60+
let result = await promise; // attende fino a quando la promise si risolve (*)
6061
*/!*
6162

62-
alert(result); // "done!"
63+
alert(result); // "fatto!"
6364
}
6465

6566
f();
6667
```
6768

68-
The function execution "pauses" at the line `(*)` and resumes when the promise settles, with `result` becoming its result. So the code above shows "done!" in one second.
69+
L'esecuzione della funzione "va in pausa" alla linea `(*)` e riprende quando la promise si ferma (settles), con `result` che diventa il suo risultato. Così il codice sopra mostra "fatto!" in un secondo.
6970

70-
Let's emphasize: `await` literally makes JavaScript wait until the promise settles, and then go on with the result. That doesn't cost any CPU resources, because the engine can do other jobs meanwhile: execute other scripts, handle events etc.
71+
Enfatizziamo: `await` fa letteralmente attendere JavaScript fino a quando la promise si ferma, poi va avanti con il risultato. Questo non costa alcuna risorsa della CPU, perché il motore può fare altri lavori nel frattempo: eseguire altri script, gestire eventi etc.
7172

72-
It's just a more elegant syntax of getting the promise result than `promise.then`, easier to read and write.
73+
È giusto una sintassi più elegante per ottenere il risultato della promise di `promise.then`, più facile da leggere e da scrivere.
7374

7475
````warn header="Can't use `await` in regular functions"
75-
If we try to use `await` in non-async function, there would be a syntax error:
76+
Se proviamo ad utilizzare `await` in una funzione non asincrona, ci sarebbe un errore di sintassi:
7677

7778
```js run
7879
function f() {
@@ -83,22 +84,22 @@ function f() {
8384
}
8485
```
8586

86-
We will get this error if we do not put `async` before a function. As said, `await` only works inside an `async function`.
87+
Avremo questo errore se non mettiamo `async` prima di una funzione. Come detto, `await` funziona solo dentro una funzione asincrona (`async function`).
8788
````
8889
89-
Let's take the `showAvatar()` example from the chapter <info:promise-chaining> and rewrite it using `async/await`:
90+
Prendiamo l'esempio `showAvatar()` dal capitolo <info:promise-chaining> e riscriviamolo usando `async/await`:
9091
91-
1. We'll need to replace `.then` calls with `await`.
92-
2. Also we should make the function `async` for them to work.
92+
1. Avremo bisogno di sostituire le chiamate `.then` con `await`.
93+
2. Inoltre dovremo rendere la funzione asincrona (`async`) per farli lavorare.
9394
9495
```js run
9596
async function showAvatar() {
9697
97-
// read our JSON
98+
// legge il nostro JSON
9899
let response = await fetch('/article/promise-chaining/user.json');
99100
let user = await response.json();
100101
101-
// read github user
102+
// legge l'utente GitHub
102103
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
103104
let githubUser = await githubResponse.json();
104105
@@ -119,18 +120,18 @@ async function showAvatar() {
119120
showAvatar();
120121
```
121122
122-
Pretty clean and easy to read, right? Much better than before.
123+
Piuttosto pulito e facile da leggere, vero? Molto meglio che prima.
123124
124-
````smart header="`await` won't work in the top-level code"
125-
People who are just starting to use `await` tend to forget the fact that we can't use `await` in top-level code. For example, this will not work:
125+
````smart header="`await` Non funzionerà nel codice di livello più alto"
126+
Le persone che hanno appena iniziato ad utilizzare `await` tendono a dimenticare il fatto che non possiamo utilizzare `await` nel codice di livello piú alto. Per esempio, questo non funzionerà:
126127
127128
```js run
128129
// syntax error in top-level code
129130
let response = await fetch('/article/promise-chaining/user.json');
130131
let user = await response.json();
131132
```
132133
133-
We can wrap it into an anonymous async function, like this:
134+
Possiamo "avvolgerlo" wrap in una funzione async anonima, come qui:
134135
135136
```js run
136137
(async () => {
@@ -142,10 +143,10 @@ We can wrap it into an anonymous async function, like this:
142143
143144
144145
````
145-
````smart header="`await` accepts \"thenables\""
146-
Like `promise.then`, `await` allows to use thenable objects (those with a callable `then` method). The idea is that a 3rd-party object may not be a promise, but promise-compatible: if it supports `.then`, that's enough to use with `await`.
146+
````smart header="`await` accetta i \"thenables\""
147+
Come `promise.then`, `await` permette di usare gli oggetti "thenable" (quelli con un metodo `then` chiamabile). L' idea è che un oggetto di terze parti possa non essere una promise, ma essere promise-compatibile: se supporta `.then`, è abbastanza per usarlo con `await`.
147148

148-
Here's a demo `Thenable` class, the `await` below accepts its instances:
149+
Ecco una dimostrazione: la classe `Thenable` class, l'`await` sotto accetta:
149150

150151
```js run
151152
class Thenable {
@@ -154,25 +155,25 @@ class Thenable {
154155
}
155156
then(resolve, reject) {
156157
alert(resolve);
157-
// resolve with this.num*2 after 1000ms
158+
// risolve con this.num*2 dopo 1000ms
158159
setTimeout(() => resolve(this.num * 2), 1000); // (*)
159160
}
160161
};
161162

162163
async function f() {
163-
// waits for 1 second, then result becomes 2
164+
// attende per 1 secondo, poi il risultato diventa 2
164165
let result = await new Thenable(1);
165166
alert(result);
166167
}
167168

168169
f();
169170
```
170171

171-
If `await` gets a non-promise object with `.then`, it calls that method providing native functions `resolve`, `reject` as arguments. Then `await` waits until one of them is called (in the example above it happens in the line `(*)`) and then proceeds with the result.
172+
Se `await` riceve un oggetto non-promise con `.then`, chiama quel metodo passando le funzioni native `resolve`, `reject` come argomenti. Poi `await` fino a quando una delle due viene chiamata (nell'esempio sopra avviene nella linea `(*)`) e poi procede con il risultato.
172173
````
173174
174-
````smart header="Async class methods"
175-
To declare an async class method, just prepend it with `async`:
175+
````smart header="Methods async delle classi"
176+
Per dichiarare un metodo async di una classe, basta precederlo con `async`:
176177
177178
```js run
178179
class Waiter {
@@ -187,14 +188,14 @@ new Waiter()
187188
.wait()
188189
.then(alert); // 1
189190
```
190-
The meaning is the same: it ensures that the returned value is a promise and enables `await`.
191+
Il significato è lo stesso: assicura che il valore ritornato sia una promise ed abilita `await`.
191192
192193
````
193-
## Error handling
194+
## Gestione degli errori
194195

195-
If a promise resolves normally, then `await promise` returns the result. But in case of a rejection, it throws the error, just as if there were a `throw` statement at that line.
196+
Se una promise si risolve normalmente, allora `await promise` ritorna il risultato. Ma nel caso di un rigetto (rejection), solleva l'errore, proprio come se in quella linea ci fosse stato un `throw`.
196197

197-
This code:
198+
Questo codice:
198199

199200
```js
200201
async function f() {
@@ -204,7 +205,7 @@ async function f() {
204205
}
205206
```
206207

207-
...Is the same as this:
208+
...È lo stesso di questo:
208209

209210
```js
210211
async function f() {
@@ -214,9 +215,9 @@ async function f() {
214215
}
215216
```
216217

217-
In real situations, the promise may take some time before it rejects. In that case there will be a delay before `await` throws an error.
218+
Nelle situazioni reali, la promise può prendere del tempo prima di venire rigettata. In quel caso ci sarà un ritardo prima che `await` sollevi un errore.
218219

219-
We can catch that error using `try..catch`, the same way as a regular `throw`:
220+
Possiamo catturare l'errore utilizzando `try..catch`, allo stesso modo che con un regolare `throw`:
220221

221222
```js run
222223
async function f() {
@@ -233,7 +234,7 @@ async function f() {
233234
f();
234235
```
235236

236-
In case of an error, the control jumps to the `catch` block. We can also wrap multiple lines:
237+
In caso di errore, il controllo salta al blocco `catch`. Possiamo anche "avvolgere" (wrap) più linee:
237238

238239
```js run
239240
async function f() {
@@ -242,66 +243,66 @@ async function f() {
242243
let response = await fetch('/no-user-here');
243244
let user = await response.json();
244245
} catch(err) {
245-
// catches errors both in fetch and response.json
246+
// cattura gli errori sia in fetch che in response.json
246247
alert(err);
247248
}
248249
}
249250

250251
f();
251252
```
252253

253-
If we don't have `try..catch`, then the promise generated by the call of the async function `f()` becomes rejected. We can append `.catch` to handle it:
254+
Se non abbiamo `try..catch`, allora la promise generata dalla chiamata della funzione async `f()` viene rigettata. Possiamo aggiungere `.catch` per gestirla:
254255

255256
```js run
256257
async function f() {
257258
let response = await fetch('http://no-such-url');
258259
}
259260

260-
// f() becomes a rejected promise
261+
// f() diventa una promise rigettata
261262
*!*
262263
f().catch(alert); // TypeError: failed to fetch // (*)
263264
*/!*
264265
```
265266

266-
If we forget to add `.catch` there, then we get an unhandled promise error (viewable in the console). We can catch such errors using a global event handler as described in the chapter <info:promise-error-handling>.
267+
Se ci dimentichiamo di aggiungere `.catch` qui, allora otteremo un errore di una promise non gestito (visibile nella console). Possiamo catturare usando un gestore di eventi globale come descritto nel capitolo <info:promise-error-handling>.
267268

268269

269270
```smart header="`async/await` and `promise.then/catch`"
270-
When we use `async/await`, we rarely need `.then`, because `await` handles the waiting for us. And we can use a regular `try..catch` instead of `.catch`. That's usually (not always) more convenient.
271+
Quando usiamo `async/await`, raramente abbiamo bisogno di `.then`, perchè `await` gestisce l'attesa per noi. E possiamo usare un normale `try..catch` invece di `.catch`. Questo è spesso (non sempre) più conveniente.
271272

272-
But at the top level of the code, when we're outside of any `async` function, we're syntactically unable to use `await`, so it's a normal practice to add `.then/catch` to handle the final result or falling-through errors.
273+
Ma al livello più alto del codice, quando siamo fuori da qualunque funzione `async`, non siamo sintatticamente in grado id usare `await`, così è una pratica normale usare `.then/catch` per gestire il risultato finale degli errori che "cadono attraverso" (falling-through).
273274

274-
Like in the line `(*)` of the example above.
275+
Come nella linea `(*)` dell'esempio sopra.
275276
```
276277
277-
````smart header="`async/await` works well with `Promise.all`"
278-
When we need to wait for multiple promises, we can wrap them in `Promise.all` and then `await`:
278+
````smart header="`async/await` funziona bene con `Promise.all`"
279+
Quando dobbiamo attendere per più promise, possiamo avvolgerle (wrap) in `Promise.all` e poi attendere (`await`):
279280
280281
```js
281-
// wait for the array of results
282+
// attende per l'array dei risultati
282283
let results = await Promise.all([
283284
fetch(url1),
284285
fetch(url2),
285286
...
286287
]);
287288
```
288289

289-
In case of an error, it propagates as usual: from the failed promise to `Promise.all`, and then becomes an exception that we can catch using `try..catch` around the call.
290+
In caso di errore, si propaga come di solito: dalla promise fallita a `Promise.all`, poi diventa una eccezione che possiamo catturare usando `try..catch` attorno alla chiamata.
290291

291292
````
292293
293-
## Summary
294+
## Riassunto
294295
295-
The `async` keyword before a function has two effects:
296+
La parola chiave `async` prima di una funzione ha due effetti:
296297
297-
1. Makes it always return a promise.
298-
2. Allows to use `await` in it.
298+
1. Fa sempre ritornare una promise.
299+
2. Permette di usare `await` al suo interno.
299300
300-
The `await` keyword before a promise makes JavaScript wait until that promise settles, and then:
301+
La parola chiave `await` prima di una promise fa attendere JavaScript fino a quando la promise è ferma, e poi:
301302
302-
1. If it's an error, the exception is generated, same as if `throw error` were called at that very place.
303-
2. Otherwise, it returns the result.
303+
1. Se c'è un errore, l'eccezione è generata, come se `throw error` fosse stato chiamato in quel punto.
304+
2. Altrimenti, ritorna il risultato.
304305
305-
Together they provide a great framework to write asynchronous code that is easy both to read and write.
306+
Insieme forniscono una ottima struttura per scrivere codice asincrono che sia facile sia da leggere che da scrivere.
306307
307-
With `async/await` we rarely need to write `promise.then/catch`, but we still shouldn't forget that they are based on promises, because sometimes (e.g. in the outermost scope) we have to use these methods. Also `Promise.all` is a nice thing to wait for many tasks simultaneously.
308+
Con `async/await` raramente avremo bisogno di scrivere `promise.then/catch`, ma comunque non dovremo dimenticare che sono sempre basate su promise, perché a volte (e.s. nello scope più esterno) dovremo usare questi metodi. Inoltre `Promise.all` è una buona cosa per attendere per più task contemporaneamente.

0 commit comments

Comments
 (0)