public function then(callable $onFulfilled = null, callable $onRejected = null) { if ($this->state === self::PENDING) { $p = new Promise(null, [$this, 'cancel']); $this->handlers[] = [$p, $onFulfilled, $onRejected]; $p->waitList = $this->waitList; $p->waitList[] = $this; return $p; } // Return a fulfilled promise and immediately invoke any callbacks. if ($this->state === self::FULFILLED) { return $onFulfilled ? promise_for($this->result)->then($onFulfilled) : promise_for($this->result); } // It's either cancelled or rejected, so return a rejected promise // and immediately invoke any callbacks. $rejection = rejection_for($this->result); return $onRejected ? $rejection->then(null, $onRejected) : $rejection; }
/** @internal */ function __next_coroutine($yielded, \Generator $generator) { return promise_for($yielded)->then(function ($value) use($generator) { $nextYield = $generator->send($value); return $generator->valid() ? __next_coroutine($nextYield, $generator) : $value; }, function ($reason) use($generator) { $nextYield = $generator->throw(exception_for($reason)); // The throw was caught, so keep iterating on the coroutine return __next_coroutine($nextYield, $generator); }); }
private function addPending() { if (!$this->iterable || !$this->iterable->valid()) { return false; } $promise = promise_for($this->iterable->current()); $idx = $this->iterable->key(); $this->pending[$idx] = $promise->then(function ($value) use($idx) { if ($this->onFulfilled) { call_user_func($this->onFulfilled, $value, $idx, $this->aggregate); } $this->step($idx); }, function ($reason) use($idx) { if ($this->onRejected) { call_user_func($this->onRejected, $reason, $idx, $this->aggregate); } $this->step($idx); }); return true; }