DEV Community

artydev
artydev

Posted on • Edited on

Run Concurrent Tasks With a Limit Using Pure JavaScript

In his article Maxim Orlov shows an astonishing way to implement concurent tasks in Javascript

It's all based on the fact that iterators objects are consumed when they are iterated, through a loop for example.

So if you run multiple loops an the same iterator, you are assured that an item will be retrieved only once

Here is a demo ConurentTastUsingIterators:

function delay(ms) {
  return new Promise((res,err) => {
    setTimeout (res, ms)
  })
}

async function doWork(iterator) {
  for  (const value of iterator) {
    await delay(1000)
    console.log(value)
  }
}

const iterator = Array.from('abcdefghi').values();

// Run async tasks with a concurrency limit of 3
const workers = new Array(3).fill(iterator).map(doWork);

// Wait until all tasks are done
Promise.allSettled(workers).then(() => console.log('Done!')); 

Enter fullscreen mode Exit fullscreen mode

Top comments (0)