PHP code example of reactphp-x / asyncify

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

    

reactphp-x / asyncify example snippets


use ReactphpX\Asyncify\Asyncify;

// 初始化进程池(可选)
Asyncify::init(1, 1); // 最小1个进程,最大1个进程

// 异步执行并获取结果
Asyncify::call(function () {
    return json_encode(['hello' => 'world']);
})->then(function ($data) {
    var_dump($data);
}, function ($e) {
    var_dump($e->getMessage());
});

Asyncify::call(function () {
    return file_get_contents('path/to/file.txt');
})->then(function ($data) {
    var_dump($data);
});

$stream = Asyncify::call(function ($stream) {
    $i = 0;
    $timer = Loop::addPeriodicTimer(1, function () use ($stream, &$i) {
        $i++;
        $stream->write('hello world:'. $i);
    });
    
    Loop::addTimer(5, function () use ($timer, $stream) {
        Loop::cancelTimer($timer);
        $stream->end();
    });
    return $stream;
}, true);

$stream->on('data', function ($data) {
    var_dump($data);
});