Example #1
0
 /**
  * @param callable $callback Callback function to execute. This function may return a Generator written as a
  *     coroutine or return an Awaitable. If the the awaitable or coroutine is rejected, the rejection reason will
  *     be thrown from this function.
  * @param mixed ...$args Arguments given to the provided callback function.
  *
  * @return bool Returns true if the loop was stopped and events still remain in the loop, false if the loop ran to
  *     completion (that is, the loop ran until no events remained).
  */
 function execute(callable $callback, ...$args) : bool
 {
     return Loop\run(function () use($callback, $args) {
         $result = $callback(...$args);
         if ($result instanceof \Generator) {
             $result = new Coroutine($result);
         } else {
             $result = Awaitable\resolve($result);
         }
         $result->done();
     });
 }
 * @return Generator
 * @throws \Steelbot\TelegramBotApi\Exception\TelegramBotApiException
 */
function botCoroutine() : \Generator
{
    $api = new Api(getenv('BOT_TOKEN'));
    $updateId = 1;
    printf("Waiting for updates ...\n");
    while (true) {
        // waiting for updates from telegram server
        /** @var Update[] $updates */
        $updates = (yield from $api->getUpdates($updateId));
        foreach ($updates as $update) {
            $method = processUpdate($update);
            if (is_object($method)) {
                yield from $api->execute($method);
            }
            $updateId = $update->updateId;
        }
    }
}
$coroutine = new Coroutine(botCoroutine());
$coroutine->done(null, function (\Throwable $exception) {
    echo "Exception catched:\n";
    echo "    Code: {$exception->getCode()}\n";
    echo "    Message: {$exception->getMessage()}\n";
    echo "    File: {$exception->getFile()}\n";
    echo "    Line: {$exception->getLine()}\n";
});
Loop\run();
 function testResolveToLastYieldPromise()
 {
     $ok = false;
     $promise = new Promise();
     coroutine(function () use($promise) {
         (yield 'fail');
         (yield $promise);
         $hello = 'hi';
     })->then(function ($value) use(&$ok) {
         $ok = $value;
         $this->fail($reason);
     });
     $promise->fulfill('omg it worked');
     Loop\run();
     $this->assertEquals('omg it worked', $ok);
 }
Example #4
0
 function testRaceReject()
 {
     $promise1 = new Promise();
     $promise2 = new Promise();
     $finalValue = 0;
     Promise\race([$promise1, $promise2])->then(function ($value) use(&$finalValue) {
         $finalValue = $value;
     }, function ($value) use(&$finalValue) {
         $finalValue = $value;
     });
     $promise1->reject(1);
     Loop\run();
     $this->assertEquals(1, $finalValue);
     $promise2->reject(2);
     Loop\run();
     $this->assertEquals(1, $finalValue);
 }