Laravel: asynchronous Guzzle requests using promises

What is a promise

A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its then() method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Source: Guzzle Promises.

How to do an asynchronous request

  • start a request using getAsync(), which will return a promise.
  • do other things
  • when you need the request result, wait for it to finish with the 'wait()' method, which will also return the request response

Note: getAsync() also needs two functions:

  • the first one is called if the request is successful
  • the second one is called if the request fails

Example

$client = new \GuzzleHttp\Client();
 
// start request
$promise = $client->getAsync('http://loripsum.net/api')->then(
    function ($response) {
        return $response->getBody();
    }, function ($exception) {
        return $exception->getMessage();
    }
);
 
// do other things
echo '<b>This will not wait for the previous request to finish to be displayed!</b>';
 
// wait for request to finish and display its response
$response = $promise->wait();
echo $response;

Example 2: two Guzzle requests in parallel

  • Start the second request without waiting for the first one to finish
  • Wait for both to finish
$client = new \GuzzleHttp\Client();
 
$promise1 = $client->getAsync('http://loripsum.net/api')->then(
    function ($response) {
        return $response->getBody();
    }, function ($exception) {
        return $exception->getMessage();
    }
);
 
$promise2 = $client->getAsync('http://loripsum.net/api')->then(
    function ($response) {
        return $response->getBody();
    }, function ($exception) {
        return $exception->getMessage();
    }
);
 
$response1 = $promise1->wait();
$response2 = $promise2->wait();
 
echo $response1;
echo $response2

Feedback