Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I access variables within a Guzzle promise "then"?

I’m trying to make use of Guzzle to send two POST requests one after another (first to create a user, then to assign them a segment) and I seem to be struggling with accessing the variables I’ve defined throughout.

I’ve got the following in my function:

$data = [
    'email' => $email,
];

if (!empty($name)) {
    $data['fname'] = $name;
}

$request = $api->postAsync('v1/subscribers', [
    'auth' => [$account_data['api_key'], ''],
    'headers' => [
        'Content-Type' => 'application/json',
    ],
    'body' => json_encode([
        'first_name' => $data['fname'] ?? '',
        'email' => $data['email'],
    ]),
]);

$request->then(
    function (ResponseInterface $res) {
        $api->post('v1/subscribers/' . $data['email'] . '/segments', [
            'auth' => [$account_data['api_key'], ''],
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode([
                'segment_ids' => [$list_id],
            ]),
        ]);
    }
);

$request->wait();

The variables $account_data and $api are defined higher up in my function and I’m able to access them when I created the initial promise using Guzzle (and it creates the user), but, when I try to use $api again inside of .then() it tells me that it is undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I access $api (without global) / what am I missing here?

>Solution :

You cannot use variables defined outside of the anonymous function without either passing them as parameters, or by explicitly importing them with a use() statement. So your function would need to look something like:

$request->then(
    function (ResponseInterface $res) use ($api, $data, $account_data, $list_id) {
        $api->post('v1/subscribers/' . $data['email'] . '/segments', [
            'auth' => [$account_data['api_key'], ''],
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode([
                'segment_ids' => [$list_id],
            ]),
        ]);
    }
);

See: Example #3 in the docs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading