RN Lez 03: Moduli, Async/Await e Template Literals
Docs: MDN JavaScript Guide
Obiettivi
Section titled “Obiettivi”- Usare import/export tra file
- Capire Promise e async/await
- Usare template literals e ternary operator
1. Template Literals (approfondimento)
Section titled “1. Template Literals (approfondimento)”const nome = 'Mario';const eta = 17;
// Baseconst msg1 = `Ciao ${nome}!`;
// Espressioniconst msg2 = `Tra 5 anni avrai ${eta + 5} anni`;
// Multi-linea (senza \n)const msg3 = ` Nome: ${nome} Età: ${eta} Maggiorenne: ${eta >= 18 ? 'Sì' : 'No'}`;
// Chiamare funzioniconst msg4 = `Ciao ${nome.toUpperCase()}!`;Ternary operator (if inline)
Section titled “Ternary operator (if inline)”// JavaScriptconst status = eta >= 18 ? 'Maggiorenne' : 'Minorenne';
// Equivalente Python: status = "Maggiorenne" if eta >= 18 else "Minorenne"2. Import/Export moduli
Section titled “2. Import/Export moduli”Esportare
Section titled “Esportare”export const somma = (a, b) => a + b;export const PI = 3.14159;
export default function saluta(nome) { return `Ciao ${nome}!`;}Importare
Section titled “Importare”import saluta, { somma, PI } from './utils/matematica';// ↑ default ↑ named export
console.log(saluta('Mario')); // Ciao Mario!console.log(somma(2, 3)); // 5| Export type | Export | Import |
|---|---|---|
| Default | export default funzione | import nome from 'path' |
| Named | export const x = 1 | import { x } from 'path' |
| Misto | export default fn + export const x | import fn, { x } from 'path' |
3. Promise — operazioni asincrone
Section titled “3. Promise — operazioni asincrone”Una Promise rappresenta un’operazione che non è ancora finita.
// Creare una Promiseconst ritardo = (ms) => { return new Promise((resolve) => { setTimeout(resolve, ms); // dopo ms, chiama resolve });};
// Usare .then()console.log('Prima');ritardo(2000).then(() => { console.log('Dopo 2 secondi');});
// Catena di .then()fetch('https://api.esempio.com/dati') .then(response => response.json()) .then(data => console.log(data)) .catch(err => console.error(err));4. Async/Await — sintassi moderna
Section titled “4. Async/Await — sintassi moderna”La sintassi async/await rende le Promise leggibili come codice sincrono.
// Funzione asincronaconst caricaDati = async () => { try { const response = await fetch('https://api.esempio.com/dati'); const data = await response.json(); return data; } catch (error) { console.error('Errore:', error); }};
// Usoconst dati = await caricaDati();Confronto
Section titled “Confronto”// .then() — vecchio stilefetch(url) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.log(err));
// async/await — moderno ✅const carica = async () => { try { const res = await fetch(url); const data = await res.json(); console.log(data); } catch (err) { console.log(err); }};5. setTimeout e setInterval
Section titled “5. setTimeout e setInterval”// Dopo 2 secondisetTimeout(() => { console.log('Sono passati 2 secondi');}, 2000);
// Ogni 1 secondoconst id = setInterval(() => { console.log('Tick!');}, 1000);
// FermareclearInterval(id);6. Tabella riassuntiva
Section titled “6. Tabella riassuntiva”| Concetto | Codice |
|---|---|
| Template literal | `Ciao ${nome}` |
| Ternary | cond ? 'Sì' : 'No' |
| Default export | export default fn |
| Named export | export const x = ... |
| Promise | new Promise((resolve) => { ... }) |
| async/await | const fn = async () => { await ... } |
| setTimeout | setTimeout(fn, ms) |
7. Esercizio
Section titled “7. Esercizio”🎯 “Countdown timer”
Section titled “🎯 “Countdown timer””Crea una funzione countdown(secondi) che:
- Usa
setIntervalper stampare il conto alla rovescia ogni secondo - Quando arriva a 0, stampa “Tempo scaduto!”
- Usa
clearIntervalper fermare
Bonus: trasformalo in una Promise che si risolve quando il countdown finisce.