Created
January 17, 2018 00:39
-
-
Save jefersondaniel/faebdcfb091916dec5b34a5174fdab09 to your computer and use it in GitHub Desktop.
exemplo-promises.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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