-
-
Notifications
You must be signed in to change notification settings - Fork 3
Async event loop
PHP is a procedural language — it won’t call your Deferred
's processing function automatically. For your promises to resolve, you’ll need an event loop to run the pending processes.
This could be a simple loop like:
while($runner->hasPendingTasks()) {
$runner->tick();
}
For production use, consider using a solution built for looping PHP. PHP.GT/async is the complementary library for handling asynchronous looping, which is built to coordinate these tasks efficiently in real-world PHP environments.
To set up an example loop using PHP.GT/async, create a new Timer...
use Gt\Async\PeriodicTimer;
$timer = new PeriodicTimer(0.1, true);
$timer->addCallback(function() {
echo ".";
});
...attach the Timer and your Deferred to the Loop...
use Gt\Async\Loop;
$loop = new Loop();
$loop->addTimer($timer);
/** @var Gt\Promise\Deferred $deferred This is the Deferred object you created. **/
$loop->addDeferredToTimer($deferred);
...and once everything is completed, you can run the loop, and everything will run asynchronously as the timer ticks:
$loop->run();
For a complex real-world codebase that heavily uses Async and Promises, please see PHP.GT/Fetch, a non-blocking HTTP client that replicates the web standard Fetch protocol in PHP.
PHP.GT/Promise is a separately maintained component of PHP.GT/WebEngine.