Using Guzzle promises asyncronously

半世苍凉 提交于 2019-12-04 07:06:52

By using wait() you're forcing the promise to be resolved synchronously: https://github.com/guzzle/promises#synchronous-wait

According to the Guzzle FAQ you should use requestAsync() with your RESTful calls:

Can Guzzle send asynchronous requests?

Yes. You can use the requestAsync, sendAsync, getAsync, headAsync, putAsync, postAsync, deleteAsync, and patchAsync methods of a client to send an asynchronous request. The client will return a GuzzleHttp\Promise\PromiseInterface object. You can chain then functions off of the promise.

$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(function ($response) {
echo 'Got a response! ' . $response->getStatusCode(); });

You can force an asynchronous response to complete using the wait() method of the returned promise.

$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$response = $promise->wait();

This question is a little old but I see no answer, so I'll give it a shot, maybe someone will find it helpful.

You can use the function all($promises).

I can't find documentation about this function but you can find its implementation here.

The comment above this function starts like this:

Given an array of promises, return a promise that is fulfilled when all the items in the array are fulfilled.

Sounds like what you are looking for, so you can do something like this:

$then = microtime(true);
$promises = [];

$promises[] = new Promise(
    function() use (&$promise) {
        //Make a request to an http server
        $httpResponse = 200;
        sleep(5);
        $promise->resolve($httpResponse);
    });

$promises[] = new Promise(
    function() use (&$promise2) {
        //Make a request to an http server
        $httpResponse = 200;
        sleep(5);
        $promise2->resolve($httpResponse);
    });

all($promises)->wait();
echo 'Took: ' . (microtime(true) - $then);

If this function isn't the one that helps you solve your problem, there are other interesting functions in that file like some($count, $promises), any($promises) or settle($promises).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!