@cleah/parallel

2.0.3 • Public • Published

Basic Usage

Execute a fixed number tasks.

  import pool from '@cleah/parallel'
  // run 10 tasks with 1 worker
  await pool(1, 10, function(i){
    console.log(`Executing task ${i}`);
  });

Execute tasks in array.

  await pool(1, [1,2,3,4,5], function(i){
    console.log(`Executing task ${i}`);
  });

Execute tasks with more workers.

  await pool(3, 10, async function(i){
    return new Promise(resolve => {
      setTimeout(()=>{
        console.log(`Executed task ${i}.`);
        resolve();
      }, Math.random() * 2000);
    })
  });

Loading more tasks

  let index = 0;
  let source = {
    items: [], // init items to execute
    async load(){ // async function to load more
      // load next 4 items
      let data = [];
      for (let i = 0; i < 4 && index < 100; i++){
        data.push({
          id: index++,
          sth: {}
        });
      }

      if (data.length){
        return data;
      } else {
        return null; // return null to stop loading
      }
    }
  }

  await pool(2, source, async function(task){
    return new Promise(resolve => {
      setTimeout(()=>{
        console.log(`Executed task ${task.id}.`);
        resolve();
      }, Math.random() * 2000);
    })
  });

Cancel running tasks

Return false in callback to cancel all running tasks.

  await pool(2, 10, function(i){
    console.log(`Executing task ${i}`);
    if (i > 5){
      return false;
    }
  });

Readme

Keywords

Package Sidebar

Install

npm i @cleah/parallel

Weekly Downloads

4

Version

2.0.3

License

ISC

Unpacked Size

19.6 kB

Total Files

15

Last publish

Collaborators

  • cleah