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
In the task <info:task/animate-circle>an animated growing circle is shown.
4
+
Nel task <info:task/animate-circle>è mostrato un cerchio crescente animato.
5
5
6
-
Now let's say we need not just a circle, but to show a message inside it. The message should appear *after* the animation is complete (the circle is fully grown), otherwise it would look ugly.
6
+
Ora diciamo che non vogliamo solo un cerchio, ma anche mostrare un messaggio al suo interno. Il messaggio dovrebbe apparire *dopo* che l'animazione è completa (il cerchio è cresciuto del tutto), altrimenti sarebbe brutto.
7
7
8
-
In the solution of the task, the function`showCircle(cx, cy, radius)`draws the circle, but gives no way to track when it's ready.
8
+
Nella soluzione del task, la funzione`showCircle(cx, cy, radius)`disegna il cerchio, ma non da modo di tracciare quando è pronto.
9
9
10
-
Add a callback argument: `showCircle(cx, cy, radius, callback)`to be called when the animation is complete. The`callback`should receive the circle `<div>`as an argument.
10
+
Aggiungi un argomento callback: `showCircle(cx, cy, radius, callback)`da chiamare quando l'animazione è completa. La`callback`dovrebbe il `<div>`cerchio come argomento.
11
11
12
-
Here's the example:
12
+
Ecco l'esempio:
13
13
14
14
```js
15
15
showCircle(150, 150, 100, div=> {
@@ -22,4 +22,4 @@ Demo:
22
22
23
23
[iframe src="solution" height=260]
24
24
25
-
Take the solution of the task <info:task/animate-circle>as the base.
25
+
Prendi la soluzione task <info:task/animate-circle>come base.
For instance, take a look at the function`loadScript(src)`:
7
+
Per esempio, guardiamo la funzione`loadScript(src)`:
8
8
9
9
```js
10
10
functionloadScript(src) {
@@ -14,40 +14,42 @@ function loadScript(src) {
14
14
}
15
15
```
16
16
17
-
The purpose of the function is to load a new script. When it adds the`<script src="…">`to the document, the browser loads and executes it.
17
+
Lo scopo della funzione è quello di caricare un nuovo script. Quando aggiunge il tag`<script src="…">`al documento, il browser lo caricherà ed eseguirà.
18
18
19
-
We can use it like this:
19
+
Possiamo usare la funzione in questo modo:
20
20
21
21
```js
22
-
//loads and executes the script
22
+
//carica ed esegue lo script
23
23
loadScript('/my/script.js');
24
24
```
25
25
26
-
The function is called "asynchronously," because the action (script loading) finishes not now, but later.
26
+
La funzione è chiamata "asincronamente", perché l'azione (il caricamento dello script) non finirà adesso ma in seguito.
27
27
28
-
The call initiates the script loading, then the execution continues. While the script is loading, the code below may finish executing, and if the loading takes time, other scripts may run meanwhile too.
28
+
La chiamata alla funzione da inizio al caricamento dello script, poi l'esecuzione continua. Mentre lo script sta caricando, il codice sotto potrebbe finire l'esecuzione, e se il caricamento richiede tempo, anche altri script potrebbero venire eseguiti nel frattempo.
29
29
30
30
```js
31
31
loadScript('/my/script.js');
32
-
//the code below loadScript doesn't wait for the script loading to finish
32
+
//il codice sotto loadScript non attende che il caricamento di loadScript sia completo
33
33
// ...
34
34
```
35
35
36
-
Now let's say we want to use the new script when it loads. It probably declares new functions, so we'd like to run them.
36
+
Ora diciamo che vogliamo eseguire il nuovo script quando carica. Probabilmente dichiarerà nuove funzioni, quindi vorremmo eseguirle.
37
37
38
-
But if we do that immediately after the`loadScript(…)`call, that wouldn't work:
38
+
Ma se lo facciamo immediatamente dopo la chiamata`loadScript(…)`non funzionerebbe:
39
39
40
40
```js
41
-
loadScript('/my/script.js'); //the script has "function newFunction() {…}"
41
+
loadScript('/my/script.js'); //lo script ha "function newFunction() {…}"
42
42
43
43
*!*
44
-
newFunction(); //no such function!
44
+
newFunction(); //nessuna funzione!
45
45
*/!*
46
46
```
47
47
48
-
Naturally, the browser probably didn't have time to load the script. So the immediate call to the new function fails. As of now, the `loadScript` function doesn't provide a way to track the load completion. The script loads and eventually runs, that's all. But we'd like to know when it happens, to use new functions and variables from that script.
48
+
Naturalmente, con buona probabilità il browser non ha avuto tempo di caricare lo script.
49
+
Quindi la chiamata immediata alla nuova funzione fallirà. Allo stato attuale la funzione `loadScript` non prevede un modo di tracciare l'avvenuto caricamento.
50
+
Lo script carica e poi viene eseguito, questo è quanto. Ma vorremmo sapere quando accade in modo da utilizzare nuove funzioni e variabili da quello script.
49
51
50
-
Let's add a`callback`function as a second argument to `loadScript`that should execute when the script loads:
52
+
Aggiungiamo una funzione`callback`come secondo argomento a `loadScript`che dovrebbe essere eseguito una volta che lo script è stato caricato.
51
53
52
54
```js
53
55
functionloadScript(src, *!*callback*/!*) {
@@ -62,19 +64,19 @@ function loadScript(src, *!*callback*/!*) {
62
64
}
63
65
```
64
66
65
-
Now if we want to call new functions from the script, we should write that in the callback:
67
+
Ora se volessimo chiamare nuove funzioni dallo script, dovremmo scriverlo nella callback:
66
68
67
69
```js
68
70
loadScript('/my/script.js', function() {
69
-
//the callback runs after the script is loaded
70
-
newFunction(); //so now it works
71
+
//la callback viene eseguita dopo che lo script caricato
72
+
newFunction(); //quindi adesso funziona
71
73
...
72
74
});
73
75
```
74
76
75
-
That's the idea: the second argument is a function (usually anonymous) that runs when the action is completed.
77
+
Questa è l'idea: il secondo argomento è una funzione (solitamente anonima) che viene eseguita quando l'azione è completata.
76
78
77
-
Here's a runnable example with a real script:
79
+
Ecco un esempio eseguibile con un vero script:
78
80
79
81
```js run
80
82
functionloadScript(src, callback) {
@@ -87,20 +89,20 @@ function loadScript(src, callback) {
alert( _ ); //function declared in the loaded script
92
+
alert( _ ); //funzione dichiatata nello script caricato
91
93
});
92
94
*/!*
93
95
```
94
96
95
-
That's called a "callback-based" style of asynchronous programming. A function that does something asynchronously should provide a `callback`argument where we put the function to run after it's complete.
97
+
Questo è lo stile di programmazione asincrona "callback-based". Una funzione che fa qualcosa asincronamente dovrebbe prevedere un argomento `callback`in cui mettiamo la funzione da eseguire al completamento dell'operazione asincrona.
96
98
97
-
Here we did it in `loadScript`, but of course, it's a general approach.
99
+
In questo esempio lo abbiamo fatto in `loadScript` ma, ovviamente, è un approccio generale.
98
100
99
-
## Callback in callback
101
+
## Callback dentro callback
100
102
101
-
How can we load two scripts sequentially: the first one, and then the second one after it?
103
+
Come possiamo caricare due script sequenzialmente: prima il primo e dopo il secondo?
102
104
103
-
The natural solution would be to put the second `loadScript`call inside the callback, like this:
105
+
La soluzione naturale sarebbe quella di mettere la seconda chiamata `loadScript`all'interno della callback in questo modo:
So, every new action is inside a callback. That's fine for few actions, but not good for many, so we'll see other variants soon.
141
+
Quindi, ogni nuova azione è dentro una callback. Questo va bene quando abbiamo poche azioni, ma non quando ne abbiamo molte, quindi in seguito vedremo altre alternative.
140
142
141
-
## Handling errors
143
+
## Gestione degli errori
142
144
143
-
In the above examples we didn't consider errors. What if the script loading fails? Our callback should be able to react on that.
145
+
Negli esempi precedenti non abbiamo considerato gli errori. Cosa accade se il caricamento dello script fallisce? La nostra callback dovrebbe essere in grado di gestire questa eventualità.
144
146
145
-
Here's an improved version of`loadScript`that tracks loading errors:
147
+
Ecco una versione migliorata di`loadScript`che traccia gli errori di caricamento:
146
148
147
149
```js run
148
150
functionloadScript(src, callback) {
@@ -151,39 +153,39 @@ function loadScript(src, callback) {
Once again, the recipe that we used for`loadScript`is actually quite common. It's called the "error-first callback" style.
176
+
Ancora una volta, la ricetta che abbiamo usato per`loadScript`è abbastanza comune. È chiamato "error-first callback" style.
175
177
176
-
The convention is:
177
-
1.The first argument of the `callback`is reserved for an error if it occurs. Then `callback(err)` is called.
178
-
2.The second argument (and the next ones if needed) are for the successful result. Then `callback(null, result1, result2…)` is called.
178
+
La convenzione è:
179
+
1.Il primo argomento di `callback`è riservato per un errore se si verifica. In questo caso la chiamata è `callback(err)`.
180
+
2.Il secondo argomento (e quelli successivi se necessario) sono per il risultato in caso di successo. In questo caso la chiamata è `callback(null, result1, result2…)`.
179
181
180
-
So the single `callback`function is used both for reporting errors and passing back results.
182
+
Quindi la singola funzione `callback`è usata sia per riportare gli errori che per passare i risultati.
181
183
182
-
## Pyramid of Doom
184
+
## Piramide del fato (Pyramid of Doom)
183
185
184
-
From the first look, it's a viable way of asynchronous coding. And indeed it is. For one or maybe two nested calls it looks fine.
186
+
Ad una prima occhiata, è un modo pratico di programmare in modo asincrono. Ed infatti lo è. Per una, forse due, chiamate annidate sembra che funzioni.
185
187
186
-
But for multiple asynchronous actions that follow one after another we'll have code like this:
188
+
Ma per molte azioni asincrone che si susseguono una dopo l'altra avremo codice come questo:
3.We load `3.js`, then if there's no error -- do something else`(*)`.
218
+
Nel codice sopra:
219
+
1.Carichiamo `1.js`, poi se non ci sono errori.
220
+
2.Carichiamo `2.js`, poi se non ci sono errori.
221
+
3.Carichiamo `3.js`, poi se non ci sono errori -- facciamo qualcos'altro`(*)`.
220
222
221
-
As calls become more nested, the code becomes deeper and increasingly more difficult to manage, especially if we have a real code instead of`...`, that may include more loops, conditional statements and so on.
223
+
Mano a mano che le chiamate diventano più annidate, il codice diventa più profondo e via via più complicato da gestire, specialmente se abbiamo codice reale invece di`...`, che può includere più cicli, condizioni e così via.
222
224
223
-
That's sometimes called "callback hell" or "pyramid of doom."
225
+
Questo viene chiamato "callback hell" o "pyramid of doom."
224
226
225
227

226
228
227
-
The "pyramid" of nested calls grows to the right with every asynchronous action. Soon it spirals out of control.
229
+
La "piramide" di chiamate annidate cresce verso destra per ogni azione asincrona. Presto la situazione sarà fuori controllo.
228
230
229
-
So this way of coding isn't very good.
231
+
Per questo motivo questo modo di programmare non è molto ottimale.
230
232
231
-
We can try to alleviate the problem by making every action a standalone function, like this:
233
+
Possiamo provare ad alleviare il problema rendendo ogni azione una funzione a se stante come qui:
232
234
233
235
```js
234
236
loadScript('1.js', step1);
@@ -255,17 +257,17 @@ function step3(error, script) {
255
257
if (error) {
256
258
handleError(error);
257
259
} else {
258
-
// ...continue after all scripts are loaded (*)
260
+
// ...continua dopo che tutti gli script sono caricati(*)
259
261
}
260
262
};
261
263
```
262
264
263
-
See? It does the same, and there's no deep nesting now because we made every action a separate top-level function.
265
+
Visto? Fa la stessa cosa, e non ci sono annidamenti profondi perché abbiamo reso ogni azione una funzione separata di primo livello.
264
266
265
-
It works, but the code looks like a torn apart spreadsheet. It's difficult to read, and you probably noticed that one needs to eye-jump between pieces while reading it. That's inconvenient, especially if the reader is not familiar with the code and doesn't know where to eye-jump.
267
+
Funziona ma il codice sembra un foglio di lavoro diviso. È difficile da leggere e probabilmente hai notato che bisogna saltare con lo sguardo tra i vari pezzi quando lo si legge. Non è conveniente, in particolare se il lettore non è familiare con il codice e non sa dove saltare con lo sguardo.
266
268
267
-
Also, the functions named`step*`are all of single use, they are created only to avoid the "pyramid of doom." No one is going to reuse them outside of the action chain. So there's a bit of a namespace cluttering here.
269
+
Inoltre, le funzioni chiamate`step*`sono tutte usate una sola volta, sono create solo per evitare la "pyramid of doom." Nessuno le riutilizzerà al di fuori della catena di azioni. Quindi abbiamo un po' di inquinamento del namespace.
268
270
269
-
We'd like to have something better.
271
+
Ci piacerebbe avere qualcosa di meglio.
270
272
271
-
Luckily, there are other ways to avoid such pyramids. One of the best ways is to use "promises," described in the next chapter.
273
+
Fortunatamente, ci sono altri modi di evitare queste piramidi. Uno dei modi migliori è di usare le "promise" descritte nel capitolo successivo.
The second call to `resolve` is ignored, because only the first call of`reject/resolve`is taken into account. Further calls are ignored.
3
+
La seconda chiamata a 'resolve' è ignorata, perché solo la prima chiamata a`reject/resolve`viene presa in considerazione. Le chiamate successive sono ignorate.
0 commit comments