Skip to content

Commit da5cc7b

Browse files
authored
Merge pull request #1 from javascript-tutorial/master
Sync with upstream
2 parents 48cc4be + 74edf7b commit da5cc7b

File tree

6 files changed

+191
-188
lines changed

6 files changed

+191
-188
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11

22
# Animated circle with callback
33

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

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

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

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

12-
Here's the example:
12+
Ecco l'esempio:
1313

1414
```js
1515
showCircle(150, 150, 100, div => {
@@ -22,4 +22,4 @@ Demo:
2222

2323
[iframe src="solution" height=260]
2424

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.

Diff for: 1-js/11-async/01-callbacks/article.md

+64-62
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11

22

3-
# Introduction: callbacks
3+
# Introduzione: callbacks
44

5-
Many actions in JavaScript are *asynchronous*.
5+
Molte azioni in JavaScript sono *asincrone*
66

7-
For instance, take a look at the function `loadScript(src)`:
7+
Per esempio, guardiamo la funzione `loadScript(src)`:
88

99
```js
1010
function loadScript(src) {
@@ -14,40 +14,42 @@ function loadScript(src) {
1414
}
1515
```
1616

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

19-
We can use it like this:
19+
Possiamo usare la funzione in questo modo:
2020

2121
```js
22-
// loads and executes the script
22+
// carica ed esegue lo script
2323
loadScript('/my/script.js');
2424
```
2525

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

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

3030
```js
3131
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
3333
// ...
3434
```
3535

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

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

4040
```js
41-
loadScript('/my/script.js'); // the script has "function newFunction() {…}"
41+
loadScript('/my/script.js'); // lo script ha "function newFunction() {…}"
4242

4343
*!*
44-
newFunction(); // no such function!
44+
newFunction(); // nessuna funzione!
4545
*/!*
4646
```
4747

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

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

5254
```js
5355
function loadScript(src, *!*callback*/!*) {
@@ -62,19 +64,19 @@ function loadScript(src, *!*callback*/!*) {
6264
}
6365
```
6466

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

6769
```js
6870
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
7173
...
7274
});
7375
```
7476

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

77-
Here's a runnable example with a real script:
79+
Ecco un esempio eseguibile con un vero script:
7880

7981
```js run
8082
function loadScript(src, callback) {
@@ -87,20 +89,20 @@ function loadScript(src, callback) {
8789
*!*
8890
loadScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js', script => {
8991
alert(`Cool, the ${script.src} is loaded`);
90-
alert( _ ); // function declared in the loaded script
92+
alert( _ ); // funzione dichiatata nello script caricato
9193
});
9294
*/!*
9395
```
9496

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

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

99-
## Callback in callback
101+
## Callback dentro callback
100102

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?
102104

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

105107
```js
106108
loadScript('/my/script.js', function(script) {
@@ -116,9 +118,9 @@ loadScript('/my/script.js', function(script) {
116118
});
117119
```
118120

119-
After the outer `loadScript` is complete, the callback initiates the inner one.
121+
Dopo che la funzione `loadScript` più esterna è completata, la callback comincia quella interna.
120122

121-
What if we want one more script...?
123+
Ma se volessimo un altro script...?
122124

123125
```js
124126
loadScript('/my/script.js', function(script) {
@@ -127,7 +129,7 @@ loadScript('/my/script.js', function(script) {
127129

128130
*!*
129131
loadScript('/my/script3.js', function(script) {
130-
// ...continue after all scripts are loaded
132+
// ...continua quando tutti gli script sono stati caricati
131133
});
132134
*/!*
133135

@@ -136,13 +138,13 @@ loadScript('/my/script.js', function(script) {
136138
});
137139
```
138140

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

141-
## Handling errors
143+
## Gestione degli errori
142144

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

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

147149
```js run
148150
function loadScript(src, callback) {
@@ -151,39 +153,39 @@ function loadScript(src, callback) {
151153

152154
*!*
153155
script.onload = () => callback(null, script);
154-
script.onerror = () => callback(new Error(`Script load error for ${src}`));
156+
script.onerror = () => callback(new Error(`Errore di caricamento dello script per ${src}`));
155157
*/!*
156158

157159
document.head.append(script);
158160
}
159161
```
160162

161-
It calls `callback(null, script)` for successful load and `callback(error)` otherwise.
163+
Chiama `callback(null, script)` per i caricamenti con successo e `callback(error)` altrimenti.
162164

163-
The usage:
165+
L'utilizzo:
164166
```js
165167
loadScript('/my/script.js', function(error, script) {
166168
if (error) {
167-
// handle error
169+
// gestione dell'errore
168170
} else {
169-
// script loaded successfully
171+
// script caricato con successo
170172
}
171173
});
172174
```
173175

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

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…)`.
179181

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

182-
## Pyramid of Doom
184+
## Piramide del fato (Pyramid of Doom)
183185

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

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

188190
```js
189191
loadScript('1.js', function(error, script) {
@@ -202,7 +204,7 @@ loadScript('1.js', function(error, script) {
202204
handleError(error);
203205
} else {
204206
*!*
205-
// ...continue after all scripts are loaded (*)
207+
// ...continua dopo che tutti gli script sono caricati (*)
206208
*/!*
207209
}
208210
});
@@ -213,22 +215,22 @@ loadScript('1.js', function(error, script) {
213215
});
214216
```
215217

216-
In the code above:
217-
1. We load `1.js`, then if there's no error.
218-
2. We load `2.js`, then if there's no error.
219-
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 `(*)`.
220222

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

223-
That's sometimes called "callback hell" or "pyramid of doom."
225+
Questo viene chiamato "callback hell" o "pyramid of doom."
224226

225227
![](callback-hell.png)
226228

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

229-
So this way of coding isn't very good.
231+
Per questo motivo questo modo di programmare non è molto ottimale.
230232

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

233235
```js
234236
loadScript('1.js', step1);
@@ -255,17 +257,17 @@ function step3(error, script) {
255257
if (error) {
256258
handleError(error);
257259
} else {
258-
// ...continue after all scripts are loaded (*)
260+
// ...continua dopo che tutti gli script sono caricati(*)
259261
}
260262
};
261263
```
262264

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

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

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

269-
We'd like to have something better.
271+
Ci piacerebbe avere qualcosa di meglio.
270272

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.
+2-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
The output is: `1`.
1+
L'output è: '1'.
22

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

Diff for: 1-js/11-async/02-promise-basics/01-re-resolve/task.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11

2-
# Re-resolve a promise?
2+
# Ri-risolvere (re-resolve) una promise?
33

44

5-
What's the output of the code below?
5+
Qual è l'output del codice sotto?
66

77
```js
88
let promise = new Promise(function(resolve, reject) {

Diff for: 1-js/11-async/02-promise-basics/02-delay-promise/solution.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ function delay(ms) {
33
return new Promise(resolve => setTimeout(resolve, ms));
44
}
55

6-
delay(3000).then(() => alert('runs after 3 seconds'));
6+
delay(3000).then(() => alert('Viene eseguita dopo 3 secondi'));
77
```
88

9-
Please note that in this task `resolve` is called without arguments. We don't return any value from `delay`, just ensure the delay.
9+
È da notare che in questo task, `resolve` è chiamato senza argomenti. Non ritorniamo alcun valore da `delay`, ci assicuriamo solo del ritardo.

0 commit comments

Comments
 (0)