File: promise.php

package info (click to toggle)
php-sabre-event 3.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 260 kB
  • sloc: php: 1,840; makefile: 15
file content (100 lines) | stat: -rwxr-xr-x 1,921 bytes parent folder | download
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
93
94
95
96
97
98
99
100
#!/usr/bin/php
<?php

use Sabre\Event\Promise;
use Sabre\Event\Loop;
use function Sabre\Event\coroutine;

require 'Sabre/Event/autoload.php';

/**
 * This example shows demonstrates the Promise api.
 */


/* Creating a new promise */
$promise = new Promise();

/* After 2 seconds we fulfill it */
Loop\setTimeout(function() use ($promise) {

    echo "Step 1\n";
    $promise->fulfill("hello");

}, 2);


/* Callback chain */

$result = $promise
    ->then(function($value) {

        echo "Step 2\n";
        // Immediately returning a new value.
        return $value . " world";

    })
    ->then(function($value) {

        echo "Step 3\n";
        // This 'then' returns a new promise which we resolve later.
        $promise = new Promise();

        // Resolving after 2 seconds
        Loop\setTimeout(function() use ($promise, $value) {

            $promise->fulfill($value . ", how are ya?");

        }, 2);

        return $promise;
    })
    ->then(function($value) {

        echo "Step 4\n";
        // This is the final event handler.
        return $value . " you rock!";
         
    })
    // Making all async calls synchronous by waiting for the final result.
    ->wait();

echo $result, "\n";

/* Now an identical example, this time with coroutines. */

$result = coroutine(function() {

    $promise = new Promise();

    /* After 2 seconds we fulfill it */
    Loop\setTimeout(function() use ($promise) {

        echo "Step 1\n";
        $promise->fulfill("hello");

    }, 2);

    $value = (yield $promise);

    echo "Step 2\n";
    $value .= ' world';

    echo "Step 3\n";
    $promise = new Promise();
    Loop\setTimeout(function() use ($promise, $value) {

        $promise->fulfill($value . ", how are ya?");

    }, 2);

    $value = (yield $promise);

    echo "Step 4\n";

    // This is the final event handler.
    yield $value . " you rock!";

})->wait();

echo $result, "\n";