How can I make a http client request after another is completed?

1.6k views Asked by At

In my Symfony function I am creating a folder, and inside this folder another folder:

$client = HttpClient::create();

$createFolder = $client->request('MKCOL', $path.$foldername, [
'auth_basic' => [$user, $authKey],
]);


$createImageFolder = $client->request('MKCOL', $path.$foldername/images', [
'auth_basic' => [$user, $authKey],
]);

It works well, but somtimes the first folder is not created fast enough, and the image folder cannot be created. Is there a way, that the second request can wait, until the first folder is created?

2

There are 2 answers

8
Barmar On BEST ANSWER

$client->request() is asynchronous. You can use $client->getStatusCode() to wait for the response before going to the next operation. You can also use this to confirm that the first operation was successful.

$client = HttpClient::create();

$createFolder = $client->request('MKCOL', $path.$foldername, [
    'auth_basic' => [$user, $authKey],
]);

$code = $createFolder->getStatusCode();
if ($code < 300) { // Creation was successful
    $createImageFolder = $client->request('MKCOL', $path.$foldername/images', [
        'auth_basic' => [$user, $authKey],
    ]);
}
0
0stone0 On

From the Symfony HTTP Client docs:

Responses are always asynchronous, so that the call to the method returns immediately instead of waiting to receive the response:

<?php
// code execution continues immediately; it doesn't wait to receive the response
$response = $client->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso');

// getting the response headers waits until they arrive
$contentType = $response->getHeaders()['content-type'][0];

// trying to get the response content will block the execution until
// the full response content is received
$content = $response->getContent();

So you'll need to call $response->getContent() (or any other like getHeaders()) to block until receiving!