Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add coroutine support #24

Open
wants to merge 2 commits into
base: 2.x.x
Choose a base branch
from
Open

add coroutine support #24

wants to merge 2 commits into from

Conversation

kpicaza
Copy link
Member

@kpicaza kpicaza commented Jun 12, 2021

Description

Add coroutine support to allow running async code in a sync flow:

Pros

  • It allows using promises like synchronous code.

Cons

  • Consumes more memory than promises
  • Is a little slower than promises

Example:

PSR-7 Request Handler

Promise Based

<?php
declare(strict_types = 1);

namespace App;

use Antidot\React\PromiseResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function React\Promise\resolve;

class SomeRequestHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return new PromiseResponse(resolve($request)->then(
            function(ServerRequestInterface $request): ResponseInterface {
                return new Response('Hello World!!!');
            }
        ));
    }
}

Coroutine based

<?php
declare(strict_types = 1);

namespace App;

use Antidot\React\PromiseResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function React\Promise\resolve;

class SomeRequestHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return PromiseResponse::fromGeneratorCallback(
            function(ServerRequestInterface $request): \Generator {
                $message = yield resolve('Hello World!!!');
            
                return new Response($message);
            }
        ));
    }
}

@kpicaza kpicaza added the enhancement New feature or request label Jun 12, 2021
@kpicaza kpicaza added this to the 2.0.0 milestone Jun 12, 2021
@kpicaza kpicaza force-pushed the coroutines branch 2 times, most recently from c8e7432 to e7ab882 Compare June 12, 2021 16:27
@kpicaza kpicaza self-assigned this Jun 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant