مرکزی مواد پر جائیں
eLearner.app
ماڈیول 8 · سبق 4 از 4کورس میں 32/32~15 min
ماڈیول اسباق (4/4)

چیلنج: وعدوں کے ساتھ شیڈولنگ

"Scheduling" means deciding how to run a list of async tasks: all together, one at a time, or in small groups. We will combine Promise.all, for await, and closures.

In parallel: all together

When tasks are independent and fast, launch them all and wait with 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]

Total time ≈ time of the slowest task.

In series: one at a time

When each task depends on the previous one, or you want to rate-limit:

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

Total time ≈ sum of the times.

With a concurrency limit

Sometimes you do not want a thousand concurrent requests, but you do not want to wait for them in series either: you want a maximum of N in flight.

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;
}

The idea: you launch n "workers" that grab the next index until there is nothing left.

Try it

ورزش#js.m8.l4.e1
کوششیں: 0لوڈ ہو رہا ہے…

Define `inSeries(tasks)` async: given an array of functions returning Promises, run them one at a time (await) and return the array of results in execution order.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

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

3 کوششوں کے بعد حل دستیاب ہے۔

Review exercise

ورزش#js.m8.l4.e2
کوششیں: 0لوڈ ہو رہا ہے…

Define `inParallel(tasks)` async: given an array of functions returning Promises, launch them all in parallel and return an array of results in the same order as the input. Use Promise.all.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

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

3 کوششوں کے بعد حل دستیاب ہے۔