@@ -98,7 +98,14 @@ function ($error) use (&$exception, &$rejected, &$wait) {
9898function parallel (array $ tasks )
9999{
100100 $ pending = array ();
101- $ deferred = new Deferred ();
101+ $ deferred = new Deferred (function () use (&$ pending ) {
102+ foreach ($ pending as $ promise ) {
103+ if ($ promise instanceof CancellablePromiseInterface) {
104+ $ promise ->cancel ();
105+ }
106+ }
107+ $ pending = array ();
108+ });
102109 $ results = array ();
103110 $ errored = false ;
104111
@@ -148,7 +155,13 @@ function parallel(array $tasks)
148155 */
149156function series (array $ tasks )
150157{
151- $ deferred = new Deferred ();
158+ $ pending = null ;
159+ $ deferred = new Deferred (function () use (&$ pending ) {
160+ if ($ pending instanceof CancellablePromiseInterface) {
161+ $ pending ->cancel ();
162+ }
163+ $ pending = null ;
164+ });
152165 $ results = array ();
153166
154167 /** @var callable():void $next */
@@ -157,7 +170,7 @@ function series(array $tasks)
157170 $ next ();
158171 };
159172
160- $ next = function () use (&$ tasks , $ taskCallback , $ deferred , &$ results ) {
173+ $ next = function () use (&$ tasks , $ taskCallback , $ deferred , &$ results, & $ pending ) {
161174 if (0 === count ($ tasks )) {
162175 $ deferred ->resolve ($ results );
163176 return ;
@@ -166,6 +179,7 @@ function series(array $tasks)
166179 $ task = array_shift ($ tasks );
167180 $ promise = call_user_func ($ task );
168181 assert ($ promise instanceof PromiseInterface);
182+ $ pending = $ promise ;
169183
170184 $ promise ->then ($ taskCallback , array ($ deferred , 'reject ' ));
171185 };
@@ -181,10 +195,16 @@ function series(array $tasks)
181195 */
182196function waterfall (array $ tasks )
183197{
184- $ deferred = new Deferred ();
198+ $ pending = null ;
199+ $ deferred = new Deferred (function () use (&$ pending ) {
200+ if ($ pending instanceof CancellablePromiseInterface) {
201+ $ pending ->cancel ();
202+ }
203+ $ pending = null ;
204+ });
185205
186206 /** @var callable $next */
187- $ next = function ($ value = null ) use (&$ tasks , &$ next , $ deferred ) {
207+ $ next = function ($ value = null ) use (&$ tasks , &$ next , $ deferred, & $ pending ) {
188208 if (0 === count ($ tasks )) {
189209 $ deferred ->resolve ($ value );
190210 return ;
@@ -193,6 +213,7 @@ function waterfall(array $tasks)
193213 $ task = array_shift ($ tasks );
194214 $ promise = call_user_func_array ($ task , func_get_args ());
195215 assert ($ promise instanceof PromiseInterface);
216+ $ pending = $ promise ;
196217
197218 $ promise ->then ($ next , array ($ deferred , 'reject ' ));
198219 };
0 commit comments