Create a new thread with your function, and keep it ready to be called as many times as you need, asynchronously in the background, without blocking your main thread event loop.
- Generate/Destroy threaded functions on demmand.
- Execute your functions as a regular async function call.
- Unlease the power of multithreading keeping your code clean.
- Compatible with Promise.race() & Promise.all()
- Availability to use Transfereable Objects and sharedArrayBuffers.
- Browser support : Firefox 59, Edge 41, Chrome 65
- Node support... ¿Soon?
let myParallelFunction = new ParallelFunction( myFunction );
- myFunction function,required : Function to be injected in the worker. If it has no name defined, it will be declared inside the worker as self._parallelFunction, otherwise the name will be respected. Async functions are accepted. Read the section Details to find out the allowed types to be returned.
The ParallelFunction Constructor returns an interface-function, wich handles the async calls to your function.
async myParallelFunction( ...args ); // ...will execute your function
Your reference to the created ParallelFunction, contains some usefull methods, like a method to Destroy the thread, when is not anymore required.
myParallelFunction.destroy();
As well provides some methods to perform advanced implementations, combining the simple interface of the library and the native Worker API. This methods, expose the worker API. For more infomation about them, check the Mozilla documentation
myParallelFunction.postMessage( message, transferList );
myParallelFunction.onMessage( handlerFunction );
A minimal example, to interact with a ParallelFunction :
// Generate a ParallelFunction to calculate Pi,
// with customizable precision. The bigger
// is n, the longuer is going to take
let calculatePi = new ParallelFunction( function(n){
var v = 0;
for(let i=1; i<=n; i+=4) v += ( 1/i ) - ( 1/(i+2) );
return 4*v;
});
// perform the calculation, with different precisions
calculatePi(1000000).then( r=> console.log(r) );
calculatePi(1000000000).then( r=> console.log(r) );
// use the Promise await keyword inside async functions
(async function(){
let pi = await calculatePi(1000000000);
console.log( pi );
// done! destroy the reference
calculatePi.destroy();
})()
Use any of the following distribution channels:
- Embeed from a Global CDN
<script src="https://cdn.rawgit.com/colxi/parallel-function/a8abdc44/parallel-function.min.js"></script>
- Use npm
$ npm -i parallel-function
- Clone from github
https://github.com/colxi/parallel-function
-
Because each request needs to be messaged to the worker, and its result, messaged back, all interactions with the function are ASYNCHRONOUS.
-
Your Parallel Function doesn't run in the same scope where was declared , but in an isolate scope inside a worker, this means, it cannot reach any variable declared in the main thread. However has acces to all the methods of the Web Worker API
-
Only those values wich can be handled by the Structure Clone Algorithm are candidates to be passed/retrieved through the function calls.
All primitive types, Except symbols -- Boolean object -- String object -- Date -- RegExp, The lastIndex field is not preserved -- Blob -- File -- FileList -- ArrayBuffer -- ArrayBufferView, All typed arrays (like Int32Array etc.) -- ImageData -- Array -- Object, Just plain objects (e.g. from object literals) -- Map -- Set
- Because the worker allows natively powerfull interactions throught the standard Messages, this library lets you use them, in order to unlease the real power of workers (and make use of trafereable objects, sharedArrayBuffers...)
Until Workers API isn't available in Node, this library is exclusive for Browsers. Threads to track:
Worker support nodejs/node#13143
Implement createObjectURL/Blob from File API nodejs/node#16167
The mechanism is pretty simple and straight forward.
ParallelFunction = Blobs + Workers + Promises
The library injects into a new Worker, a Blob containing the code of the communication layer, and the provided function, and handles each function call adding it to the messages queue, using a unique index ID. When a call is returned, it resolves the Promise associated with the call ID.