fix api tutorial

This commit is contained in:
2026-02-16 22:19:12 +01:00
parent 4ecf8f49e9
commit c5b16b7e02
2 changed files with 57 additions and 32 deletions

View File

@@ -40,27 +40,32 @@
outputLabel: "Output Step 1:" outputLabel: "Output Step 1:"
}, },
{ {
title: "2. Prima chiamata Fetch (GET)", title: "2. Async/Await",
description: "Per usare 'await', la funzione deve essere dichiarata come 'async'.",
outputLabel: "Output Step 2:"
},
{
title: "3. Prima chiamata Fetch (GET)",
description: "Recuperiamo un oggetto JSON reale da un server pubblico.", description: "Recuperiamo un oggetto JSON reale da un server pubblico.",
outputLabel: "Dati ricevuti:" outputLabel: "Dati ricevuti:"
}, },
{ {
title: "3. Estrazione Dati (JSON)", title: "4. Estrazione Dati (JSON)",
description: "La risposta grezza non basta. Dobbiamo convertirla ed estrarre il titolo.", description: "La risposta grezza non basta. Dobbiamo convertirla ed estrarre il titolo.",
outputLabel: "Titolo del Post:" outputLabel: "Titolo del Post:"
}, },
{ {
title: "4. Gestione Errori (Try/Catch)", title: "5. Gestione Errori (Try/Catch)",
description: "Proviamo a chiamare un sito che non esiste per vedere se il codice sopravvive.", description: "Proviamo a chiamare un sito che non esiste per vedere se il codice sopravvive.",
outputLabel: "Stato operazione:" outputLabel: "Stato operazione:"
}, },
{ {
title: "5. Lavorare con le Liste (Array)", title: "6. Lavorare con le Liste (Array)",
description: "Scarichiamo 10 utenti e mostriamo solo i loro nomi.", description: "Scarichiamo 10 utenti e mostriamo solo i loro nomi.",
outputLabel: "Elenco Utenti:" outputLabel: "Elenco Utenti:"
}, },
{ {
title: "6. Invio Dati (POST)", title: "7. Invio Dati (POST)",
description: "Simuliamo l'invio di un nuovo post al server.", description: "Simuliamo l'invio di un nuovo post al server.",
outputLabel: "Risposta Server:" outputLabel: "Risposta Server:"
} }

View File

@@ -13,16 +13,28 @@ async function eseguiTutorial() {
* JavaScript di solito corre veloce. Con i server, deve aspettare. * JavaScript di solito corre veloce. Con i server, deve aspettare.
* La keyword 'await' serve a dire "Fermati qui finché l'operazione non finisce". * La keyword 'await' serve a dire "Fermati qui finché l'operazione non finisce".
*/ */
// Questa funzione simula un server che ci mette 2 secondi a rispondere // Questa funzione simula un server che ci mette 1 secondo a rispondere
// TODO: Aggiungi 'await' prima di wait(2000) per far funzionare l'attesa. // TODO: Aggiungi 'await' prima di wait(2000) per far funzionare l'attesa.
wait(2000); wait(1000);
mostraOutput(1, "Operazione completata!"); mostraOutput(1, "Operazione completata!");
/**
* ===========================================
* === 2. Async/Await ===
* Per usare 'await', la funzione deve essere dichiarata come 'async'.
* Questo è un modo elegante per scrivere codice asincrono.
* Crea una funzione async chiamata 'aspetta2Secondi' che aspetta 2 secondi (usa la funzione wait).
* Poi stampa "2 secondi sono passati!" e mostra il risultato usando mostraOutput(2, "2 secondi sono passati!").
* Chiama la funzione subito dopo averla definita.
*/
mostraOutput(2, "");
/** /**
* =========================================== * ===========================================
* === 2. Fetch Base (GET) === * === 3. Fetch Base (GET) ===
* Usiamo `fetch(url)` per chiamare un server vero. * Usiamo `fetch(url)` per chiamare un server vero.
*/ */
// TODO: crea una costante 'urlBase' con l'indirizzo dettato a lezione // TODO: crea una costante 'urlBase' con l'indirizzo dettato a lezione
@@ -31,12 +43,12 @@ async function eseguiTutorial() {
const urlBase = "https://sito-finto.com"; const urlBase = "https://sito-finto.com";
const rispostaGrezza = null; const rispostaGrezza = null;
mostraOutput(2, rispostaGrezza ? "Risposta ricevuta (Response Object)" : ""); mostraOutput(3, rispostaGrezza ? "Risposta ricevuta (Response Object)" : "");
/** /**
* =========================================== * ===========================================
* === 3. Estrarre il JSON === * === 4. Estrarre il JSON ===
* La risposta grezza contiene status code, headers, ecc. * La risposta grezza contiene status code, headers, ecc.
* A noi servono i dati. Dobbiamo usare il metodo .json(). * A noi servono i dati. Dobbiamo usare il metodo .json().
* ANCHE .json() è asincrono e vuole 'await'. * ANCHE .json() è asincrono e vuole 'await'.
@@ -51,12 +63,12 @@ async function eseguiTutorial() {
nomeUtente = "NOME MANCANTE"; nomeUtente = "NOME MANCANTE";
} }
mostraOutput(3, nomeUtente); mostraOutput(4, nomeUtente);
/** /**
* =========================================== * ===========================================
* === 4. Gestione Errori (Try / Catch) === * === 5. Gestione Errori (Try / Catch) ===
* Se il server è giù o l'URL è sbagliato, fetch esplode. * Se il server è giù o l'URL è sbagliato, fetch esplode.
* Usiamo try/catch per gestire il problema. * Usiamo try/catch per gestire il problema.
*/ */
@@ -64,31 +76,35 @@ async function eseguiTutorial() {
// TODO: Prova a fare una fetch a un URL sbagliato (es. 'https://sito-finto.com') // TODO: Prova a fare una fetch a un URL sbagliato (es. 'https://sito-finto.com')
// Ricorda l'await! // Ricorda l'await!
mostraOutput(4); mostraOutput(5);
} catch (errore) { } catch (errore) {
mostraOutput(4, errore.message); mostraOutput(5, errore.message);
} }
/** /**
* =========================================== * ===========================================
* === 5. Liste di Dati (Array) === * === 6. Liste di Dati (Array) ===
* Spesso riceviamo un array di oggetti. Dobbiamo ciclarlo. * Spesso riceviamo un array di oggetti. Dobbiamo ciclarlo.
*/ */
// Scarichiamo 5 utenti // Scarichiamo 5 utenti
const responseUtenti = await fetch(`${urlBase}/users?_limit=5`); try {
const listaUtenti = await responseUtenti.json(); const responseUtenti = await fetch(`${urlBase}/users?_limit=5`);
const listaUtenti = await responseUtenti.json();
// TODO: Usa .map() o un ciclo for per creare un array contenente SOLO i nomi degli utenti. // TODO: Usa .map() o un ciclo for per creare un array contenente SOLO i nomi degli utenti.
// Esempio: const nomi = listaUtenti.map(u => u.name); // Esempio: const nomi = listaUtenti.map(u => u.name);
const soloNomi = []; const soloNomi = [];
mostraOutput(5, soloNomi); mostraOutput(6, soloNomi);
} catch (errore) {
mostraOutput(6, "");
}
/** /**
* =========================================== * ===========================================
* === 6. Inviare Dati (POST) === * === 7. Inviare Dati (POST) ===
* Per inviare dati, fetch accetta un secondo parametro di opzioni. * Per inviare dati, fetch accetta un secondo parametro di opzioni.
*/ */
// TODO: Completa l'oggetto con i dati mancanti // TODO: Completa l'oggetto con i dati mancanti
@@ -102,14 +118,18 @@ async function eseguiTutorial() {
avatar: "https://ui-avatars.com/api/?name=Nome+Cognome" avatar: "https://ui-avatars.com/api/?name=Nome+Cognome"
}; };
// TODO: Completa la fetch. try {
// Aggiungi method: 'POST' // TODO: Completa la fetch.
// Aggiungi headers: { 'Content-Type': 'application/json' } // Aggiungi method: 'POST'
// Aggiungi body: JSON.stringify(nuovoUtente) // Aggiungi headers: { 'Content-Type': 'application/json' }
const rispInvio = await fetch(`${urlBase}/posts`, { // Aggiungi body: JSON.stringify(nuovoUtente)
const rispInvio = await fetch(`${urlBase}/posts`, {
}); });
const risultatoInvio = await rispInvio.json(); const risultatoInvio = await rispInvio.json();
mostraOutput(6, risultatoInvio); mostraOutput(7, risultatoInvio);
} catch (errore) {
mostraOutput(7, "");
}
} }