I am looping through a DB of users to pass data to an API to validate addresses via getAsync
. I need to update my DB record based on what the API returns. Problem is that I can't figure out how to pass $user->id
to the promise to update the record.
$users = User::all();
$client = new Client();
$promises = (function () use ($users, $client) {
foreach ($users as $user) {
yield $client->getAsync('https://some/api/' . $user->address);
}
})();
$eachPromise = new EachPromise($promises, [
'concurrency' => 2,
'fulfilled' => function (Response $response) {
if ($response->getStatusCode() == 200) {
//NEED TO ACCESS USER->ID HERE TO UPDATE RECORD IN DB
}
},
'rejected' => function ($reason) {
}
]);
$eachPromise->promise()->wait();
Thanks in advance!
My Answer:
To pass the $user->id to the promise and update the record in the database, you can modify the code as follows:
php
$users = User::all();
$client = new Client();
$promises = (function () use ($users, $client) {
foreach ($users as $user) {
yield $client->getAsync('https://some/api/' . $user->address)->then(function (Response $response) use ($user) {
if ($response->getStatusCode() == 200) {
// Update the record in the database using $user->id
User::where('id', $user->id)->update(['status' => 'validated']);
}
});
}
})();
$eachPromise = new EachPromise($promises, [
'concurrency' => 2,
'rejected' => function ($reason) {
// Handle rejected promises
}
]);
$eachPromise->promise()->wait();
In this code snippet, we are using the `then` method on the promise returned by `getAsync` to access the $user object within the callback function. This allows us to update the record in the database using the $user->id.
Rate this post
3 of 5 based on 6308 votesComments