user1942626
user1942626

Reputation: 835

how to retrieve post response variable outside in reactphp

My code is as follows:

require __DIR__.'/vendor/autoload.php';
use Psr\Http\Message\ResponseInterface;

$loop = React\EventLoop\Factory::create();
$client = new React\Http\Browser($loop);

$data = [
    'name' => [
        'first' => 'Alice',
        'name' => 'Smith',
    ],
    'email' => '[email protected]',
    'userid' => 'alice',
];


$client->post(
    'https://httpbin.org/post',
    [
        'Content-Type' => 'application/json',
    ],
    json_encode($data)
)->then(function (ResponseInterface $response) {
    $response = (string) $response->getBody();

    return $response;
});

**echo $response;**
$loop->run();

I am able to get the response inside then function(). but I cannot retrieve the response value outside.

I like to send multiple asynchronous POST requests and collect each responses and echo all of them at once.

How can I access the response variable from outside of post()->then()?

Upvotes: 0

Views: 116

Answers (1)

user1942626
user1942626

Reputation: 835

I could get the response when I need a response with deferred and promise method.

First, I assigned the request and response method to $promise. And I was able to simply get the response with $deferred->resolve();

require __DIR__.'/vendor/autoload.php';
use Psr\Http\Message\ResponseInterface;

$loop = React\EventLoop\Factory::create();
$client = new React\Http\Browser($loop);
$deferred = new React\Promise\Deferred();
$promise = $deferred->promise();

$data = [
    'name' => [
        'first' => 'Alice',
        'name' => 'Smith',
    ],
    'email' => '[email protected]',
    'userid' => 'alice',
];


$promise = $client->post(
    'https://httpbin.org/post',
    [
        'Content-Type' => 'application/json',
    ],
    json_encode($data)
)->then(function (ResponseInterface $response) {
    $response = (string) $response->getBody();

    return $response;
});

echo $deferred->resolve();
$loop->run();

Upvotes: 0

Related Questions