=> $complete, 'rejected' => $complete ]); $pool->promise()->wait(); For each request, we create a Promise. A Promise represents an eventual result. We wait for all Promises to be Fulfilled or Rejected Gather requests Execute request 1 Execute request 2 Execute request 3 Execute request 4 Return responses
receive them • Can’t throw exceptions because there’s nothing to catch them • Promises allow us to compose the results of async functions and handle errors from async functions. • Promises are a paradigmatic translation layer!
new React\Socket\Server($loop); $socket->on('connection', function ($conn) { usleep(500000); $conn->write(str_repeat('a', 1024)); $conn->end(); }); echo "Socket server listening on port 4000.\n"; echo "You can connect to it by running: telnet localhost 4000\n"; $socket->listen(4000); $loop->run();
new React\Socket\Server($loop); $http = new \React\Http\Server($socket); $counter = 0; $http->on( 'request', function (\React\Http\Request $request, \React\Http\Response $response) use (&$counter, &$loop) { $counter++; echo "Handling request number $counter" . PHP_EOL; $headers = ['Content-Type' => 'text/html']; $response->writeHead(200, $headers); $process = new \React\ChildProcess\Process('fortune'); $process->start($loop); $process->stdout->on( 'data', function ($output) use (&$response) { $response->write($output); } ); $process->on( 'exit', function ($rc, $signal) use (&$response) { $response->end(); } ); } ); echo "Socket server listening on port 4000.\n"; echo "You can connect to it by running: telnet localhost 4000\n"; $socket->listen(4000); $loop->run();
sync. Sometimes it’s slower. • It can be hard to conceptualize the benefits of async in the mind • It can be hard to recognize the benefits of async on a laptop