This is currently WIP, I will fill in more details but it's a good starting version that is still hopefully useful to the reader...
Recently I worked on a project that involved scheduling a number of tasks in parallel in Node.js.
Running mutiple tasks
I used the await-the library to do this.
https://github.com/olono/await-the/blob/master/lib/result.js
There are multiple ways to solve this kind of problem. Mainly you have to understand the Node.js is a single threaded environment (See Event loop) and how callbacks operate with a library like async or await-the.
Basically, here idea was that you write a function that has a callback as its last argument
```
const doTask = async (arg1, callback) {
const results = await doStuffWith(arg1) ;
callback(results);
}
```
Then perform this action on multiple inputs in parallel such as by using the excellent async.mapLimit function if you want to limit how many tasks in parallel you want to to run
async.mapLimit(items, 5, doTask)
The same result can be achieved using the await-the utility the.result
So here is how you would execute taskObject.doTask with an argument arg1 asynchronously
const results = await the.result([taskObject, 'doTask'], arg)
Now to run this against mutiple values in parallel you can use the.each (or async.each)
const doParallelTasks = async function (taskObject, valuesList) {
const results = the.each(valuesList, async value => await the.result([taskObject,'doTask'], value, { limit: 5})
return results;
}
The limit arg limits how many tasks can be run in parallel, to avoid cpu overload.
Now each doTask instance will be promisified and awaited on, all results will be collected in results array.
Testing this code using Sinon stubs
Testing this code using a stub needs a trick since the callback function must be invoked for the.each to function correctlyCreate a stub that calls the callback in some way, at least something like this
const stubFcn = sinon.stub().callsFake((arg, callback) => callback())
One way to to unit test the logic of doParallelTasks is to ensure that taskObject is called as many times as you expect
const stubFcn = sinon.stub().callsFake((arg, callback) => callback())
const results = doParallelTasks(taskObject, [value1, value2]);
assert(results.length).to.be(2);
Comments
Post a Comment