Skip to content

Commit ca4c692

Browse files
committed
Ensure parallel() function stops invoking additional tasks on error
1 parent 98ae760 commit ca4c692

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

src/functions.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ function parallel(array $tasks)
102102

103103
$done = function () use (&$results, &$errors, $deferred) {
104104
if (count($errors)) {
105-
$deferred->reject(array_shift($errors));
105+
$deferred->reject(reset($errors));
106106
return;
107107
}
108108

@@ -116,7 +116,7 @@ function parallel(array $tasks)
116116
}
117117

118118
$checkDone = function () use (&$results, &$errors, $numTasks, $done) {
119-
if ($numTasks === count($results) + count($errors)) {
119+
if ($numTasks === count($results) || count($errors)) {
120120
$done();
121121
}
122122
};
@@ -136,6 +136,10 @@ function parallel(array $tasks)
136136
assert($promise instanceof PromiseInterface);
137137

138138
$promise->then($taskCallback, $taskErrback);
139+
140+
if ($errors) {
141+
break;
142+
}
139143
}
140144

141145
return $deferred->promise();

tests/ParallelTest.php

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ function () {
2929
},
3030
function () {
3131
return new Promise(function ($resolve) {
32-
Loop::addTimer(0.1, function () use ($resolve) {
32+
Loop::addTimer(0.11, function () use ($resolve) {
3333
$resolve('bar');
3434
});
3535
});
@@ -49,7 +49,7 @@ function () {
4949
$timer->assertInRange(0.1, 0.2);
5050
}
5151

52-
public function testParallelWithError()
52+
public function testParallelWithErrorReturnsPromiseRejectedWithExceptionFromTaskAndStopsCallingAdditionalTasks()
5353
{
5454
$called = 0;
5555

@@ -60,7 +60,8 @@ function () use (&$called) {
6060
$resolve('foo');
6161
});
6262
},
63-
function () {
63+
function () use (&$called) {
64+
$called++;
6465
return new Promise(function () {
6566
throw new \RuntimeException('whoops');
6667
});
@@ -80,7 +81,7 @@ function () use (&$called) {
8081
$this->assertSame(2, $called);
8182
}
8283

83-
public function testParallelWithDelayedError()
84+
public function testParallelWithDelayedErrorReturnsPromiseRejectedWithExceptionFromTask()
8485
{
8586
$called = 0;
8687

@@ -91,7 +92,8 @@ function () use (&$called) {
9192
$resolve('foo');
9293
});
9394
},
94-
function () {
95+
function () use (&$called) {
96+
$called++;
9597
return new Promise(function ($_, $reject) {
9698
Loop::addTimer(0.001, function () use ($reject) {
9799
$reject(new \RuntimeException('whoops'));
@@ -112,6 +114,6 @@ function () use (&$called) {
112114

113115
Loop::run();
114116

115-
$this->assertSame(2, $called);
117+
$this->assertSame(3, $called);
116118
}
117119
}

0 commit comments

Comments
 (0)