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
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
+
4
5
5
6
## Async functions
6
7
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:
8
9
9
10
```js
10
11
asyncfunctionf() {
11
12
return1;
12
13
}
13
14
```
14
15
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.
16
17
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:
18
19
19
20
```js run
20
21
asyncfunctionf() {
@@ -24,7 +25,7 @@ async function f() {
24
25
f().then(alert); // 1
25
26
```
26
27
27
-
...We could explicitly return a promise, that would be the same:
28
+
...Possiamo anche ritornare esplicitamente una promise, sarebbe lo stesso:
28
29
29
30
```js run
30
31
asyncfunctionf() {
@@ -34,45 +35,45 @@ async function f() {
34
35
f().then(alert); // 1
35
36
```
36
37
37
-
So, `async`ensures that the function returns a promise, and wrapsnon-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.
38
39
39
40
## Await
40
41
41
-
The syntax:
42
+
La sintassi:
42
43
43
44
```js
44
-
//works only inside async functions
45
+
//funziona solo all'interno delle funzioni async
45
46
let value =await promise;
46
47
```
47
48
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.
49
50
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:
51
52
```js run
52
53
asyncfunctionf() {
53
54
54
55
let promise =newPromise((resolve, reject) => {
55
-
setTimeout(() =>resolve("done!"), 1000)
56
+
setTimeout(() =>resolve("fatto!"), 1000)
56
57
});
57
58
58
59
*!*
59
-
let result =await promise; //wait till the promise resolves (*)
60
+
let result =await promise; //attende fino a quando la promise si risolve (*)
60
61
*/!*
61
62
62
-
alert(result); // "done!"
63
+
alert(result); // "fatto!"
63
64
}
64
65
65
66
f();
66
67
```
67
68
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.
69
70
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.
71
72
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.
73
74
74
75
````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:
76
77
77
78
```js run
78
79
functionf() {
@@ -83,22 +84,22 @@ function f() {
83
84
}
84
85
```
85
86
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`).
87
88
````
88
89
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`:
90
91
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.
93
94
94
95
```js run
95
96
async function showAvatar() {
96
97
97
-
// read our JSON
98
+
// legge il nostro JSON
98
99
let response = await fetch('/article/promise-chaining/user.json');
99
100
let user = await response.json();
100
101
101
-
// read github user
102
+
// legge l'utente GitHub
102
103
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
103
104
let githubUser = await githubResponse.json();
104
105
@@ -119,18 +120,18 @@ async function showAvatar() {
119
120
showAvatar();
120
121
```
121
122
122
-
Pretty clean and easy to read, right? Much better than before.
123
+
Piuttosto pulito e facile da leggere, vero? Molto meglio che prima.
123
124
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à:
126
127
127
128
```js run
128
129
// syntax error in top-level code
129
130
let response = await fetch('/article/promise-chaining/user.json');
130
131
let user = await response.json();
131
132
```
132
133
133
-
We can wrap it into an anonymous async function, like this:
134
+
Possiamo "avvolgerlo" wrap in una funzione async anonima, come qui:
134
135
135
136
```js run
136
137
(async () => {
@@ -142,10 +143,10 @@ We can wrap it into an anonymous async function, like this:
142
143
143
144
144
145
````
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`.
147
148
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:
//attende per 1 secondo, poi il risultato diventa 2
164
165
let result =awaitnewThenable(1);
165
166
alert(result);
166
167
}
167
168
168
169
f();
169
170
```
170
171
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.
172
173
````
173
174
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`:
176
177
177
178
```js run
178
179
class Waiter {
@@ -187,14 +188,14 @@ new Waiter()
187
188
.wait()
188
189
.then(alert); // 1
189
190
```
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`.
191
192
192
193
````
193
-
## Error handling
194
+
## Gestione degli errori
194
195
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`.
196
197
197
-
This code:
198
+
Questo codice:
198
199
199
200
```js
200
201
asyncfunctionf() {
@@ -204,7 +205,7 @@ async function f() {
204
205
}
205
206
```
206
207
207
-
...Is the same as this:
208
+
...È lo stesso di questo:
208
209
209
210
```js
210
211
asyncfunctionf() {
@@ -214,9 +215,9 @@ async function f() {
214
215
}
215
216
```
216
217
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.
218
219
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`:
220
221
221
222
```js run
222
223
asyncfunctionf() {
@@ -233,7 +234,7 @@ async function f() {
233
234
f();
234
235
```
235
236
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:
237
238
238
239
```js run
239
240
asyncfunctionf() {
@@ -242,66 +243,66 @@ async function f() {
242
243
let response =awaitfetch('/no-user-here');
243
244
let user =awaitresponse.json();
244
245
} catch(err) {
245
-
//catches errors both in fetch and response.json
246
+
//cattura gli errori sia in fetch che in response.json
246
247
alert(err);
247
248
}
248
249
}
249
250
250
251
f();
251
252
```
252
253
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:
254
255
255
256
```js run
256
257
asyncfunctionf() {
257
258
let response =awaitfetch('http://no-such-url');
258
259
}
259
260
260
-
// f() becomes a rejected promise
261
+
// f() diventa una promise rigettata
261
262
*!*
262
263
f().catch(alert); // TypeError: failed to fetch // (*)
263
264
*/!*
264
265
```
265
266
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>.
267
268
268
269
269
270
```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.
271
272
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).
273
274
274
-
Like in the line `(*)`of the example above.
275
+
Come nella linea `(*)`dell'esempio sopra.
275
276
```
276
277
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`):
279
280
280
281
```js
281
-
// wait for the array of results
282
+
// attende per l'array dei risultati
282
283
let results = await Promise.all([
283
284
fetch(url1),
284
285
fetch(url2),
285
286
...
286
287
]);
287
288
```
288
289
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.
290
291
291
292
````
292
293
293
-
## Summary
294
+
## Riassunto
294
295
295
-
The `async` keyword before a function has two effects:
296
+
La parola chiave `async` prima di una funzione ha due effetti:
296
297
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.
299
300
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:
301
302
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.
304
305
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.
306
307
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