Send asynchronous request without waiting the response using guzzle

gmponos picture gmponos · Mar 12, 2016 · Viewed 10.4k times · Source

I have the following two functions

public function myEndpoint(){
    $this->logger->debug('Started');
    $this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait')->wait();
    $this->logger->debug("I shouldn't wait");
}

public function doNotWait(){
    sleep(10);
    $this->logger->debug("You shouldn't wait");
}

Now what I need to see in my logs is:

Started
I shouldn't wait
You shouldn't wait

But what I see

Started
You shouldn't wait
I shouldn't wait

Also I tried using the following ways:

Way #1

public function myEndpoint(){
    $this->logger->debug('Started');
    $this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait', ['synchronous' => false])->wait();
    $this->logger->debug("I shouldn't wait");
}

Way #2

public function myEndpoint(){
    $this->logger->debug('Started');
    $this->guzzle->requestAsync('post', 'http://myurl.com/doNotWait');

    $queue = \GuzzleHttp\Promise\queue()->run();
    $this->logger->debug("I shouldn't wait");
}

But the result is never the desired one. Any idea? I am using Guzzle 6.x.

Answer

cweiske picture cweiske · Jun 27, 2017

To get it off the unanswered list:


Guzzle does not support "fire and forget" asynchronous requests without deep hacking.

The async methods are abstractions for Client::requestAsync(), which returns a promise. See https://github.com/guzzle/promises#synchronous-wait - calling Promise::wait() "is used to synchronously force a promise to complete".

Reference: https://github.com/guzzle/guzzle/issues/1429#issuecomment-197119452