PHP code example of choval / async

1. Go to this page and download the library: Download choval/async 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/ */

    

choval / async example snippets


function future($i=0)
{
    return new React\Promise\FulfilledPromise($i+1);
}

future()
    ->then(function ($i) {
        return future($i);
    })
    ->then(function ($i) {
        return future($i);
    })
    ->then(function ($i) {
        return future($i);
    })
    ->then(function ($i) {
        return future($i);
    })
    ->then(function ($i) {
        echo $i;
    });

// Prints 5, but that chain nightmare...

Async\resolve(function () {
    $i = yield future();
    $i = yield future($i);
    $i = yield future($i);
    $i = yield future($i);
    $i = yield future($i);
    echo $i;
});

// Prints 5 as well ;-)

Async\resolve(function () {
    $i = 0;
    while($i<5) {
        $i = yield future($i);
    }
    echo $i;
});

$defer = new React\Promise\Deferred();
$loop->addTimer(1, function () use ($defer) {
    $defer->resolve(true);
});
$promise = $defer->promise();
$i = 0;
function future($i=0)
{   
    return new React\Promise\FulfilledPromise($i+1);
}
while(!Async\is_done($promise)) {
    $i++;
}
echo "Promise finished with $i loops\n";

$promise = Async\resolve(function () {
    yield 1;
    yield 2;
    return 'Wazza';
});
// $promise resolves with Wazza

$defer1 = new React\Promise\Deferred();
$loop->addTimer(1, function () use ($defer1) {
    $defer1->resolve('hello');
});
$defer2 = new React\Promise\Deferred();
$loop->addTimer(0.5, function () use ($defer2) {
    $defer2->resolve('world');
});

$promise = Async\resolve(function () use ($defer1, $defer2) {
    $out = [];
    $out[] = yield $defer1->promise();
    $out[] = yield $defer2->promise();
    return implode(' ', $out);
});

$promise = Async\resolve(function () {
    $fetch = [
        'bing' => 
            Async\execute('curl https://bing.com/'),
        'duckduckgo' => 
            Async\execute('curl https://duckduckgo.com/'),
        'google' => 
            Async\execute('curl https://google.com/'),
    ];
    $sources = yield React\Promise\all($fetch);
    return $sources;
});

$fn = function () {
    throw new \Exception('hey!');
};
$promise = Async\silent($fn, $e);
// Promise resolves with null
// $e will hold an the hey! exception

Async\execute('echo "Wazza"')
    ->then(function ($output) {
        // $output contains Wazza\n
    })
    ->otherwise(function ($e) {
        // Throws an Exception if the execution fails
        // ie: 127 if the command does not exist
        $exitCode = $e->getCode();
    });

$promise = Async\resolve(function () {
    $start = time();
    yield Async\sleep(2);
    $end = time();
    return $end-$start;
});
// $promise resolves in ~2 seconds

$start = time();
Async\sleep(2);
$end = time();
// $start and $end will be the same

$start = time();
Async\wait(Async\sleep(2));
$end = time();
// $end == $start+2;

$blocking_code = function ($secs) {
    sleep($secs);
    return time();
}

$secs = 1;
$promises = [];
$promises[] = Async\async($blocking_code, [$secs]);
$promises[] = Async\async($blocking_code, [$secs]);
$promises[] = Async\async($blocking_code, [$secs]);
$promises[] = Async\async($blocking_code, [$secs]);
$base = time()+$secs;

$times = Async\wait(React\Promise\all($promises));
foreach ($times as $time) {
    // $time === $base
}

Async\set_forks_limit(100);
echo Async\get_forks_limit(); // 100

$times = 5;
$func = function () use (&$times) {
    if(--$times) {
        throw new \Exception('bad error');
    }
    return 'ok';
};
$retries = 6;
Async\retry($func, $retries, 0.1, 'bad error')
    ->then(function ($res) {
        // $res is 'ok'
    });

/**
 * @param callable $func
 * @param int $retries=10 (optional)
 * @param float $frequency=0.001 (optional)
 * @param string $ignoress (optional) The Throwable class to catch or string to match against Exception->getMessage()
 *
 * @return Promise
 */

$func = function () {
    yield Async\sleep(2);
    return true;
};
Async\wait(Async\timeout($func, 1.5));
// Throws an Exception due to the timeout 1.5 < 2

Async\wait(function () {

    Async\timer(function () {
        Async\sleep(0.1);
    }, $msecs);
    print_r($msecs); // ~100ms

});

Async\wait(function () {

    $loop = 20000;
    $mem = 1024*1024*16; // 16MB
    while($loop--) {
        yield Async\waitMemory($mem);
        Async\sleep(1);
    }

});

$files = Async\wait(Async\rglob('/files/*.php', 'a'));
/*
$files has:
/files/b.php
/files/c.php
/files/1/b.php
/files/1/c.php
/files/2/b.php
/files/2/c.php
*/

$lines = Async\wait(Async\file('/etc/hosts'));
var_dump($lines);

file_get_contents
file_put_contents
file_exists
is_file
is_dir
is_link
sha1_file
md5_file
mime_content_type
realpath
fileatime
filectime
filemtime
file
filesize
copy
rename
unlink
touch
mkdir
rmdir
scandir
glob