What is the point of Guzzle async promises?

Asked
Active3 hr before
Viewed126 times

8 Answers

pointasync
90%

Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , Stack Overflow help chat ,Thanks for contributing an answer to Stack Overflow!, Meta Stack Overflow

With Guzzle, do promises provide any real utility? It seems that you must call wait(). The following code (from the docs) seems to do nothing by itself:

$promise = $client - > requestAsync('GET', 'http://httpbin.org/get');
$promise - > then(
   function(ResponseInterface $res) {
      echo $res - > getStatusCode().
      "\n";
   },
   function(RequestException $e) {
      echo $e - > getMessage().
      "\n";
      echo $e - > getRequest() - > getMethod();
   }
);
load more v
88%

How to use promise without external end point by using local function as promise. Prequisite : ,composer require guzzlehttp/guzzle ,Call promise function where you have to optimise or call promise. ,Call promise function where you have to optimise or call promise.

use GuzzleHttp\ Promise\ Promise;
use GuzzleHttp\ Promise\ EachPromise;
load more v
72%

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.,Synchronously waits on the promise to complete.,You can force a promise to resolve and not unwrap the state of the promise by passing false to the first argument of the wait function:,Calling wait on a promise that has been fulfilled will not trigger the wait function. It will simply return the previously resolved value.

use GuzzleHttp\ Promise\ Promise;

$promise = new Promise();
$promise - > then(
   // $onFulfilled
   function($value) {
      echo 'The promise was fulfilled.';
   },
   // $onRejected
   function($reason) {
      echo 'The promise was rejected.';
   }
);
load more v
65%

One of the more powerful features of the Guzzle promises library is that it allows you to use promise coroutines that make writing asynchronous workflows seem more like writing more traditional synchronous workflows. In fact, the SDK utilizes coroutine promises in most of the high level abstractions.,You can combine promises into aggregate promises to build more sophisticated workflows. The guzzlehttp/promise package contains various functions that can be used to combine promises.,The AWS SDK for PHP uses promises to allow for asynchronous workflows, and this asynchronicity allows HTTP requests to be sent concurrently. The promise specification used by the SDK is Promises/A+.,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.

$client = new Aws\ DynamoDb\ DynamoDbClient([
   'region' => 'us-west-2',
   'version' => 'latest',
]);

// This will create a promise that will eventually contain a result
$promise = $client - > describeTableAsync(['TableName' => 'mytable']);
load more v
75%

You can send requests with Guzzle using a GuzzleHttp\ClientInterface object.,You can use the GuzzleHttp\Pool object when you have an indeterminate amount of requests you wish to send.,Different implementations exist for the GuzzleHttp\Cookie\CookieJarInterface :,Guzzle can maintain a cookie session for you if instructed using the cookies request option. When sending a request, the cookies option must be set to an instance of GuzzleHttp\Cookie\CookieJarInterface.

use GuzzleHttp\ Client;

$client = new Client([
   // Base URI is used with relative requests
   'base_uri' => 'http://httpbin.org',
   // You can set any number of default request options.
   'timeout' => 2.0,
]);
load more v
40%

In this example, Guzzle waits until you absolutely need a result before blocking execution and waiting for a response. Promise\unwrap is just a fancy Guzzle function that waits for a promises in an array to be resolved before continuing. If you only have one promise, you can similarly call $promise->wait() to wait for that promise only.,Instead of that approach, I found a solution that is much simpler: create a React promise, and resolve it when the Guzzle promise resolves. Let me show you how easy it is:,We finally made it to the end! This article was rather long, but hopefully it contains some helpful information. If you have been using Guzzle and React or can think of alternate ways to integrate them, comment below and share your experiences and ideas!,Yep, that's what it looks like – a Frankenstein's hybrid of Guzzle and React promises. The above example was just the beginning; it turned out that far too much work would be required down this path because the way promises are processed is fundamentally different between Guzzle and React.

One of the core features of Guzzle 6 is an implementation of promises. For those of you that are unfamiliar with the concept of promises, here is an excellent article that gives you a gentle introduction (though it is targeted toward JavaScript). To summarize, a promise is an object that represents some value that will be determined in the future. Callbacks can be attached to the promise using a then() method which will be triggered when the promise's value becomes available. Here is a quick example on how to make an asynchronous Guzzle request:

use GuzzleHttp\ Client;
use GuzzleHttp\ Exception\ RequestException;
use Psr\ Http\ Message\ ResponseInterface;

$client = new Client();
$client - > getAsync('http://loripsum.net/api') - > then(
   function(ResponseInterface $res) {
      echo $res - > getStatusCode().
      "\n";
   },
   function(RequestException $e) {
      echo $e - > getMessage().
      "\n";
      echo $e - > getRequest() - > getMethod();
   }
);
load more v
22%

A promise represents a single result of an asynchronous operation. It is not necessarily available at a specific time, but should become in the future.,The $promise that is returned implements Http\Promise\Promise. At this point in time, the response is not known yet. You can be polite and wait for that response to arrive:,Promise Asynchronous requests Wait Then ,Asynchronous requests enable non-blocking HTTP operations. When sending asynchronous HTTP requests, a promise is returned. The promise acts as a proxy for the response or error result, which is not yet known.

$request = $messageFactory - > createRequest('GET', 'http://php-http.org');

// Where $client implements HttpAsyncClient
$promise = $client - > sendAsyncRequest($request);

// This code will be executed right after the request is sent, but before
// the response is returned.
echo 'Wow, non-blocking!';
load more v
60%

Guzzle 6: Guzzle is a PHP HTTP client helps to send the HTTP requests.These methods can be used to send the asynchronous HTTP requests.,How to make asynchronous HTTP requests in PHP ?,Asynchronous HTTP requests using Promise: A single result of an asynchronous operation represents a Promise. Asynchronous requests are used in the non-blocking of the HTTP operations. When asynchronous HTTP requests send a promise, it gets returned.,Execute a request using HTTPlug:


php composer.phar require guzzlehttp / guzzle: ~6.0

or

composer require guzzlehttp / guzzle: ~6.0

Execute a request using HTTPlug:

$request = $messageFactory - > createRequest(
   'GET', 'http://php-http.org');
$promise = $client - > sendAsyncRequest($request);
echo 'Non-blocking!';

Wait: The “promise” which is returned from the above, implements http\Promise\Promise. The response is not known yet during this point of time. Wait for that response to arrive.

try {
   $response = $promise - > wait();
} catch (\Exception $exception) {
   echo $exception - > getMessage();
}
  1. One callback that will be executed if the request turns out to be successful.
  2. Callback that will be executed if the request results in an error.
  // Success Callback
  function(ResponseInterface $response) {

     echo 'New response!';

     // Write status code to the log file
     file_put_contents('responses.log',
        $response - > getStatusCode().
        "\n", FILE_APPEND);
     return $response;
  },

  // Failure Callback
  function(\Exception $exception) {
     echo 'We have a problem';
     throw $exception;
  }

Building a multi-thread cURL request: Generally, we can handle multiple requests. First, we trigger the first one and process the response, then the second and third, and so on. But, this process is slow and time-consuming. But cURL offers the curl_multi_* functions to handle any asnyc requests.

$running = null;
$mh = curl_multi_init();

$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, 'https://endpoint.com');

// Other curl options....
curl_multi_add_handle($mh, $ch1);

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'https://endpoint.com');

// Other curl options....  
curl_multi_add_handle($mh, $ch2);

do {
   curl_multi_exec($mh, $running);
   curl_multi_select($mh);
} while ($running > 0);

$r1 = curl_multi_getcontent($ch1);
$r2 = curl_multi_getcontent($ch2);
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
load more v

Other "point-async" queries related to "What is the point of Guzzle async promises?"