Skip to content
This repository has been archived by the owner on Oct 18, 2023. It is now read-only.

Commit

Permalink
Merge pull request #37 from Financial-Times/matth/fix-semaphore
Browse files Browse the repository at this point in the history
Fix semaphore
  • Loading branch information
i-like-robots authored Mar 6, 2019
2 parents 1caf46c + be057e0 commit 927052e
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/run-parallel.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const Semaphore = require('async-sema');
const { Sema } = require('async-sema');
const logger = require('./logger');
const EventedQueue = require('./evented-queue');

module.exports = (tasks = [], concurrency = 1, preserveOrder = false) => {
const semaphore = new Semaphore(concurrency);
const semaphore = new Sema(concurrency);
const queue = new EventedQueue();

logger.info(`Executing up to ${concurrency} tasks at a time`);
Expand Down
94 changes: 94 additions & 0 deletions test/src/run-parallel.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const subject = require('../../src/run-parallel');

const wait = (ms = 10) => new Promise((resolve) => setTimeout(resolve, ms));

const noop = () => {};

function createTask(name, onStart, onEnd, time = 10, allDependencies = []) {
return {
apply: () => {
onStart();
return wait(time).then(onEnd);
},
pkg: {
name,
allDependencies
}
};
}

describe('src/run-parallel', () => {
it('executes each task', async () => {
const complete = [];

const tasks = [
createTask('a', noop, () => complete.push('a')),
createTask('b', noop, () => complete.push('b')),
createTask('c', noop, () => complete.push('c'))
];

await subject(tasks);

expect(complete.length).toEqual(3);
});

describe('with preserve order option', () => {
it('waits for dependent tasks to finish', async () => {
const complete = []

const tasks = [
createTask(
'a',
() => expect(complete.length).toEqual(0),
() => complete.push('a'),
100
),
createTask(
'b',
() => expect(complete.length).toEqual(0),
() => complete.push('b'),
10
),
createTask(
'c',
() => expect(complete).toEqual(expect.arrayContaining(['a', 'b'])),
() => complete.push('c'),
10,
['a', 'b']
)
];

await subject(tasks, 10, true);
});
});

describe('without preserve order option', () => {
it('waits for dependent tasks to finish', async () => {
const complete = []

const tasks = [
createTask(
'a',
() => expect(complete.length).toEqual(0),
() => complete.push('a'),
100
),
createTask(
'b',
() => expect(complete.length).toEqual(0),
() => complete.push('b'),
10
),
createTask(
'c',
() => expect(complete.length).toEqual(0),
() => complete.push('c'),
10,
['a', 'b']
)
];

await subject(tasks, 10, false);
});
});
});

0 comments on commit 927052e

Please sign in to comment.