ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
promise.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
3
6use function Sabre\Event\coroutine;
7
8require __DIR__ . '/../vendor/autoload.php';
9
15/* Creating a new promise */
17
18/* After 2 seconds we fulfill it */
19Loop\setTimeout(function() use ($promise) {
20
21 echo "Step 1\n";
22 $promise->fulfill("hello");
23
24}, 2);
25
26
27/* Callback chain */
28
30 ->then(function($value) {
31
32 echo "Step 2\n";
33 // Immediately returning a new value.
34 return $value . " world";
35
36 })
37 ->then(function($value) {
38
39 echo "Step 3\n";
40 // This 'then' returns a new promise which we resolve later.
41 $promise = new Promise();
42
43 // Resolving after 2 seconds
44 Loop\setTimeout(function() use ($promise, $value) {
45
46 $promise->fulfill($value . ", how are ya?");
47
48 }, 2);
49
50 return $promise;
51 })
52 ->then(function($value) {
53
54 echo "Step 4\n";
55 // This is the final event handler.
56 return $value . " you rock!";
57
58 })
59 // Making all async calls synchronous by waiting for the final result.
60 ->wait();
61
62echo $result, "\n";
63
64/* Now an identical example, this time with coroutines. */
65
66$result = coroutine(function() {
67
68 $promise = new Promise();
69
70 /* After 2 seconds we fulfill it */
71 Loop\setTimeout(function() use ($promise) {
72
73 echo "Step 1\n";
74 $promise->fulfill("hello");
75
76 }, 2);
77
78 $value = (yield $promise);
79
80 echo "Step 2\n";
81 $value .= ' world';
82
83 echo "Step 3\n";
84 $promise = new Promise();
85 Loop\setTimeout(function() use ($promise, $value) {
86
87 $promise->fulfill($value . ", how are ya?");
88
89 }, 2);
90
91 $value = (yield $promise);
92
93 echo "Step 4\n";
94
95 // This is the final event handler.
96 yield $value . " you rock!";
97
98})->wait();
99
100echo $result, "\n";
An exception for terminatinating execution or to throw for unit testing.
An implementation of the Promise pattern.
Definition: Promise.php:23
setTimeout(callable $cb, $timeout)
Executes a function after x seconds.
Definition: functions.php:12
coroutine(callable $gen)
Turn asynchronous promise-based code into something that looks synchronous again, through the use of ...
Definition: coroutine.php:47
$result
Definition: promise.php:29
$promise
This example shows demonstrates the Promise api.
Definition: promise.php:16