PHP code example of nunomaduro / pokio

1. Go to this page and download the library: Download nunomaduro/pokio library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nunomaduro / pokio example snippets


$promiseA = async(function () {
    sleep(2);
    
    return 'Task 1';
});

$promiseB = async(function () {
    sleep(2);
    
    return 'Task 2';
});

// just takes 2 seconds...
[$resA, $resB] = await([$promiseA, $promiseB]);

echo $resA; // Task 1
echo $resB; // Task 2

$promise = async(function () {
    return 1 + 1;
});

var_dump(await($promise)); // int(2)

$promise = async(fn (): int => 1 + 2)
    ->then(fn ($result): int => $result + 2)
    ->then(fn ($result): int => $result * 2);

$result = await($promise);
var_dump($result); // int(10)

$promise = async(function () {
    throw new Exception('Error');
})->catch(function (Throwable $e) {
    return 'Rescued: ' . $e->getMessage();
});

var_dump(await($promise)); // string(16) "Rescued: Error"

$promise = async(function () {
    throw new Exception('Error');
});

try {
    await($promise);
} catch (Throwable $e) {
    var_dump('Rescued: ' . $e->getMessage()); // string(16) "Rescued: Error"
}

$promise = async(function (): void {
    throw new RuntimeException('Exception 1');
})->finally(function () use (&$called): void {
    echo "Finally called\n";
});

$promise = async(function () {
    return async(function () {
        return 1 + 1;
    });
});

var_dump(await($promise)); // int(2)

$promise = async(function () {
    sleep(2);
    
    return 1 + 1;
});

var_dump(await($promise)); // int(2)

$promiseA = async(function () {
    sleep(2);
    
    return 1 + 1;
});

$promiseB = async(function () {
    sleep(2);
    
    return 2 + 2;
});

var_dump(await([$promiseA, $promiseB])); // array(2) { [0]=> int(2) [1]=> int(4) }

$promise = async(fn (): int => 1 + 2);

$result = $promise();

var_dump($result); // int(3)