Passer au contenu principal
eLearner.app
Module 8 · Leçon 4 sur 432/32 dans le cours~15 min
Leçons du module (4/4)

Sfida: scheduling con Promise

"Scheduling" significa decidere come eseguire una lista di task asincroni: tutti insieme, uno alla volta, oppure a piccoli gruppi. Combineremo Promise.all, for await e closures.

In parallelo: tutto insieme

Quando i task sono indipendenti e veloci, lanciali tutti e aspettali con Promise.all:

JS
async function inParallelo(tasks) {
  return Promise.all(tasks.map((t) => t()));
}

const risultati = await inParallelo([
  () => Promise.resolve(1),
  () => Promise.resolve(2),
  () => Promise.resolve(3),
]);
// [1, 2, 3]

Tempo totale ≈ tempo del task più lento.

In serie: uno alla volta

Quando ogni task dipende dal precedente, o vuoi rate-limit:

JS
async function inSerie(tasks) {
  const risultati = [];
  for (const t of tasks) {
    risultati.push(await t());
  }
  return risultati;
}

Tempo totale ≈ somma dei tempi.

Con limite di concorrenza

A volte non vuoi mille richieste contemporanee, ma neanche aspettarle in serie: vuoi un massimo di N in volo.

JS
async function conLimite(tasks, n) {
  const risultati = new Array(tasks.length);
  let i = 0;
  async function worker() {
    while (i < tasks.length) {
      const mio = i++;
      risultati[mio] = await tasks[mio]();
    }
  }
  await Promise.all(Array.from({ length: n }, worker));
  return risultati;
}

Idea: lanci n "worker" che si pescano l'indice successivo finché non c'è più nulla.

Prova tu

Exercice#js.m8.l4.e1
Tentatives : 0Chargement…

Definisci `inSeries(tasks)` async: dato un array di funzioni che ritornano Promise, eseguile una alla volta (await) e ritorna l'array dei risultati nell'ordine di esecuzione.

Chargement de l'éditeur…
Afficher l'indice

for ... of e push(await t())

Solution disponible après 3 tentatives

Esercizio di ripasso

Exercice#js.m8.l4.e2
Tentatives : 0Chargement…

Definisci `inParallel(tasks)` async: dato un array di funzioni che ritornano Promise, lancia tutto in parallelo e ritorna un array dei risultati nello stesso ordine dell'input. Usa Promise.all.

Chargement de l'éditeur…
Afficher l'indice

Promise.all(tasks.map((t) => t()))

Solution disponible après 3 tentatives