如何等待诺言完成

时间:2020-02-10 17:38:05

标签: php guzzle guzzle6 guzzlehttp

在另一堂课中,我有一个promise可以正常工作。我需要在另一个控制器中使用返回的数据,但是我不知道如何在另一个控制器中等待数据:

class PromiseController
{
  private function load()
  {
    $client = new \GuzzleHttp\Client();

    // variables omitted for example
    $promise = $client->requestAsync('POST', $url, $options);
    $json = null;
    $promise->then(
        function (ResponseInterface $res) {
            $xml = simplexml_load_string($res->getBody(),'SimpleXMLElement',LIBXML_NOCDATA);
            $json = json_encode($xml);
            $json = $json;
            // I see my json here. Great.
        },
        function (RequestException $e) {
            Log::info($e->getMessage());
            echo $e->getMessage() . "\n";
            echo $e->getRequest()->getMethod();
        }
    );

    $return $json;
  }
}

需要数据的控制器:


// Leaving out the function etc

$data = ( new PromiseController )->load();

return array(

  'xmlAsJson' => $data

);

返回的数据始终为null。我需要等待“所需”控制器中的数据,但是如何?我希望有一个单独的控制器,以便在将结果传递到array之前将xml处理为json。

1 个答案:

答案 0 :(得分:1)

如果您要传播异步信号,则必须继续使用Promise,因此请从您的控制器返回新的Promise:

class PromiseController
{
    private function load()
    {
        $client = new \GuzzleHttp\Client();

        $promise = $client->requestAsync('POST', $url, $options);
        $jsonPromise = $promise->then(
            function (ResponseInterface $res) {
                $xml = simplexml_load_string($res->getBody(),'SimpleXMLElement',LIBXML_NOCDATA);
                $json = json_encode($xml);

                return $json;
            },
            function (RequestException $e) {
                Log::info($e->getMessage());
                echo $e->getMessage() . "\n";
                echo $e->getRequest()->getMethod();
            }
        );

        return $jsonPromise;
  }
}

然后稍后在代码中对产生的promise调用->wait()

$data = ( new PromiseController )->load()->wait();

return array(
    'xmlAsJson' => $data
);