1

我正在尝试使用 ReactPHP 理解 Promises 的概念

$app = function ($request, $response) use ($redis, $config) {

    $promise = React\Promise\all(
        array(
            AsyncGetUser(),
            AsyncGetDB(),
            AsyncGetTemplate()
        )
    )->then(function ($res) {
        $result = ParseTemplate($user, $template, $whatever);
    }

    \React\Promise\resolve($promise);


    $response->writeHead(200, array('Content-Type' => 'text/plain'));
    $response->end($result);

}

$http->on('request', $app);

但在准备好$response之前发送。$result怎么能做类似等待的事情,$promise所以我可以$result正确发送?

我试图移动$response->endanother->then()部分,但是我没有在浏览器中得到任何响应(即脚本在 $app = function 已经完成时得到结果)。

4

1 回答 1

1

我根本不知道reactphp,但是如果promise 像JS 中的promise 一样工作,似乎你需要->then在你有结果的地方写响应!

$app = function ($request, $response) use ($redis, $config) {
    $promise = React\Promise\all(
        array(
            AsyncGetUser(),
            AsyncGetDB(),
            AsyncGetTemplate()
        )
    )->then(function ($res) {
        $result = ParseTemplate($user, $template, $whatever);
        $response->writeHead(200, array('Content-Type' => 'text/plain'));
        $response->end($result);
    }
}

$http->on('request', $app);

注意:代码中的以下行

\React\Promise\resolve($promise);

没有意义。\React\Promise\resolve并没有像您想象的那样“解决承诺”,它创建并返回一个已解决的承诺 - 您将其丢弃!

于 2017-02-09T03:05:17.067 回答