从异步PHP返回一个值


Returning a value from asynchronous PHP

我想从PHP中的异步函数返回一个值。。。我在这里使用icicle.io,但我很乐意使用任何东西,只要它能做我想做的事!不管怎样,这是下面的一些代码

<?php
require __DIR__ . '/vendor/autoload.php';
use Icicle'Coroutine'Coroutine;
use Icicle'Loop;
function getArray($int) {
    yield array ($int, $int + 1, $int + 2);
}
function getArrays() {
    $numbers = array (1, 4, 7);
    $results = array();
    foreach ($numbers as $number) {
        array_push($results, (yield(getArray($number))));
    }
    yield call_user_func_array('array_merge', $results);
}
$coroutine = new Coroutine(getArrays());
$data = $coroutine->then(
    function ($result) {
        $data = print_r($result, true);
        return "Result: {$data}'n";
    },
    function (Exception $e) {
        echo "Error: {$e->getMessage()}'n";
    }
)->done(function ($value) {
    echo $value;
});
Loop'run();

我真正想做的是把最后一点放在函数中,所以它看起来更像这样:

function sync() {
    $coroutine = new Coroutine(getArrays());
    $data = $coroutine->then(
        function ($result) {
            $data = print_r($result, true);
            return "Result: {$data}'n";
        },
        function (Exception $e) {
            echo "Error: {$e->getMessage()}'n";
        }
    )->done(function ($value) {
        return $value;
    });
    Loop'run();
    return /* the value */;
}

然后,从我的酷软件中,我可以调用sync(),就好像它是一个同步函数一样,幸福地不知道幕后发生的异步恶作剧。

有人这样做过吗,或者对我该怎么做有一些建议吗?目前,我想到的最好的是(ab)使用输出缓冲区&serialize()/unserialize()函数,但由于我做这一切都是出于提高性能的愿望,这似乎有些倒退!!

您可以使用wait()方法同步等待Awaitable(包括Coroutine)的解析。此方法在事件循环中打勾,直到解决协同程序为止。这意味着您的sync()函数可以简单地在协程对象上调用此方法并返回结果。

function sync() {
    $coroutine = new Coroutine(getArrays());
    return $coroutine->wait();
}