Skip to content

Instantly share code, notes, and snippets.

@jefersondaniel
Created January 17, 2018 00:39
Show Gist options
  • Save jefersondaniel/faebdcfb091916dec5b34a5174fdab09 to your computer and use it in GitHub Desktop.
Save jefersondaniel/faebdcfb091916dec5b34a5174fdab09 to your computer and use it in GitHub Desktop.
exemplo-promises.php
<?php
require __DIR__ . '/autoload.php';
use Amp\Loop;
use Amp\Artax\Request;
use Amp\Artax\DefaultClient;
function requestJson($url) {
return Amp\call(function () use ($url) { // A função call transforma um generator em uma promise pois o yield aceita somente promises
$client = new DefaultClient;
$request = (new Request($url))->withHeader('Accept', 'application/json');
$response = yield $client->request($request);
$body = yield $response->getBody();
return json_decode($body, true);
});
}
function getDadJokes() {
return Amp\call(function () {
$json = yield requestJson('https://icanhazdadjoke.com/search?term=food');
return array_map(function ($result) { return $result['joke']; }, $json['results']);
});
}
function getChuckNorrisJokes() {
return Amp\call(function () {
$json = yield requestJson('https://api.chucknorris.io/jokes/search?query=food');
return array_map(function ($result) { return $result['value']; }, $json['result']);
});
}
Loop::run(function () {
$response = ['results' => []];
try {
$jokeResults = yield [
'dad' => getDadJokes(),
'chuckNorris' => getChuckNorrisJokes(),
];
foreach ($jokeResults as $apiName => $jokes) {
foreach ($jokes as $joke) {
$response['results'][] = ['joke' => $joke, 'apiName' => $apiName];
}
}
} catch (Amp\Artax\HttpException $error) {
http_response_code(500);
$response['error'] = $error->getMessage();
}
echo json_encode($response);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment