Passer au contenu principal
eLearner.app
Module 7 · Leçon 2 sur 426/32 dans le cours~12 min
Leçons du module (2/4)

async / await

async/await è una sintassi più chiara per lavorare con le Promise: il codice si legge come codice sincrono, ma dietro le quinte usa esattamente le stesse Promise della lezione precedente.

async function

Una function dichiarata con async restituisce sempre una Promise.

JS
async function quaranta() {
  return 40;
}

quaranta(); // Promise { 40 }
quaranta().then((v) => console.log(v)); // 40

Anche se ritorni un valore "normale", la function lo avvolge in una Promise risolta.

await

Dentro una async function puoi mettere await davanti a una Promise: l'esecuzione si mette in pausa finché la Promise non si decide, poi prosegue con il valore risolto.

JS
async function somma() {
  const a = await Promise.resolve(10);
  const b = await Promise.resolve(20);
  return a + b; // 30
}

Equivalente in stile .then (più verboso):

JS
function somma() {
  return Promise.resolve(10).then((a) => Promise.resolve(20).then((b) => a + b));
}

await propaga gli errori

Se la Promise viene rejected, await rilancia l'errore. Puoi catturarlo con un normale try/catch:

JS
async function leggi() {
  try {
    const x = await Promise.reject(new Error('no'));
    return x;
  } catch (err) {
    return 'errore: ' + err.message;
  }
}

leggi(); // Promise { 'errore: no' }

Arrow async

JS
const raddoppia = async (n) => n * 2;
raddoppia(5); // Promise { 10 }

Prova tu

Exercice#js.m7.l2.e1
Tentatives : 0Chargement…

Definisci una `async function addOne(p)` che riceve una Promise di numero e restituisce (come Promise) il numero + 1. Usa await.

Chargement de l'éditeur…
Afficher l'indice

const n = await p; return n + 1;

Solution disponible après 3 tentatives

Esercizio di ripasso

Exercice#js.m7.l2.e2
Tentatives : 0Chargement…

Definisci `sumTwo(pa, pb)` async: riceve due Promise di numeri, ritorna la loro somma. Usa due await sequenziali.

Chargement de l'éditeur…
Afficher l'indice

await ognuna, poi return a + b.

Solution disponible après 3 tentatives