Skip to main content

Named Tasks

Piscina supports running named tasks within a single worker file. This example demonstrates how to use a dispatcher pattern to execute different operations based on the task name.

index.js
'use strict';

const Piscina = require('piscina');
const { resolve } = require('path');
const { makeTask } = require('./helper');

const piscina = new Piscina({
filename: resolve(__dirname, 'worker.js')
});

(async function () {
const result = await Promise.all([
piscina.run(makeTask('add', 4, 6)),
piscina.run(makeTask('sub', 4, 6))
]);
console.log(result);
})();

The worker file uses a dispatcher to handle different operations:

worker.js
'use strict';

const { dispatcher } = require('./helper');

module.exports = dispatcher({
add (a, b) { return a + b; },
sub (a, b) { return a - b; }
});

The helper file provides utility functions for creating tasks and dispatching them:

helper.js
function makeTask (op, ...args) {
return { op, args };
}

function dispatcher (obj) {
return async ({ op, args }) => {
return await obj[op](...args);
};
}

module.exports = {
dispatcher,
makeTask
};

You can also check out this example on github.