Skip to content

Commit eb1a3a3

Browse files
committed
Fix reduce problems.
The point to resolve the promise got determined incorrectly.
1 parent 92d5f1f commit eb1a3a3

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

SpecRunner.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
<script type="text/javascript" src="test/worker.spec.js"></script>
1616
<script type="text/javascript" src="test/eval.spec.js"></script>
1717
<script type="text/javascript" src="test/api.spec.js"></script>
18+
<script type="text/javascript" src="test/operations.spec.js"></script>
1819
<script type="text/javascript" src="test/performance.spec.js"></script>
1920

2021
<script type="text/javascript">

lib/parallel.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,12 +248,15 @@
248248
throw new Error('Can\'t reduce non-array data');
249249
}
250250

251+
var runningWorkers = 0;
251252
var that = this;
252253
function done(data) {
253-
if (that.data.length === 1) {
254+
--runningWorkers;
255+
if (that.data.length === 1 && runningWorkers === 0) {
254256
that.data = that.data[0];
255257
newOp.resolve(null, that.data);
256-
} else {
258+
} else if (that.data.length > 1) {
259+
++runningWorkers;
257260
that._spawnReduceWorker([that.data[0], that.data[1]], cb, done);
258261
that.data.splice(0, 2);
259262
}
@@ -265,6 +268,7 @@
265268
newOp.resolve(null, that.data[0]);
266269
} else {
267270
for (var i = 0; i < that.options.maxWorkers && i < Math.floor(that.data.length / 2); ++i) {
271+
++runningWorkers;
268272
that._spawnReduceWorker([that.data[i * 2], that.data[i * 2 + 1]], cb, done);
269273
}
270274

test/operations.spec.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
describe('Operations', function () {
2+
var isNode = typeof module !== 'undefined' && module.exports;
3+
var Parallel = isNode ? require('../lib/parallel.js') : self.Parallel;
4+
5+
it('should require(), map() and reduce correctly (check console errors)', function () {
6+
var p = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8]);
7+
8+
function add(d) { return d[0] + d[1]; }
9+
function factorial(n) { return n < 2 ? 1 : n * factorial(n - 1); }
10+
11+
p.require(factorial);
12+
13+
var done = false;
14+
runs(function () {
15+
p.map(function (n) { return Math.pow(10, n); }).reduce(add).then(function() {
16+
done = true;
17+
});
18+
});
19+
20+
waitsFor(function () {
21+
return done;
22+
}, "it should finish", 500);
23+
});
24+
});

0 commit comments

Comments
 (0)