-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample_001_delay_react.php
92 lines (79 loc) · 1.98 KB
/
example_001_delay_react.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
use LogicalSteps\Async\Async;
use LogicalSteps\Async\ConsoleLogger;
use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
require __DIR__ . '/../vendor/autoload.php';
/** @var LoopInterface $loop */
$loop = Factory::create();
function two_seconds(callable $call_back)
{
global $loop;
$loop->addTimer(
2,
function () use ($call_back) {
$call_back(null, true);
}
);
}
class Timer
{
public static function delay(int $seconds, callable $call_back)
{
global $loop;
$loop->addTimer(
$seconds,
function () use ($call_back) {
$call_back(null, true);
}
);
}
public function wait(int $seconds, callable $call_back)
{
global $loop;
$loop->addTimer(
$seconds,
function () use ($call_back) {
$call_back(null, true);
}
);
}
public function hold(int $seconds)
{
yield [$this, 'wait', $seconds];
return true;
}
public function promise(int $seconds)
{
global $loop;
$differed = new Deferred();
$loop->addTimer(
$seconds,
function () use ($differed, $seconds) {
$differed->resolve($seconds);
}
);
return $differed->promise();
}
}
function flow()
{
//echo 'started' . PHP_EOL;
yield 'two_seconds';
//echo 'after two seconds' . PHP_EOL;
yield ['Timer', 'delay', 8];
//echo 'after eight seconds' . PHP_EOL;
$timer = new Timer();
yield [$timer, 'wait', 3];
//echo 'after three seconds' . PHP_EOL;
yield $timer->hold(1);
//echo 'after one second' . PHP_EOL;
yield $timer->promise(2);
//echo 'after two seconds' . PHP_EOL;
return yield $timer->hold(7);
}
Async::setLogger(new ConsoleLogger());
Async::await(flow());
//Async::await(flow()); //run another session in parallel
$loop->run();