如何等待在另一堂课中完成诺言

问题描述 投票:1回答:1

在另一堂课中,我有一个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。我需要等待“所需”控制器中的数据,但是如何?我希望有一个单独的控制器来将xml处理为json,然后再将结果传递给array

php guzzle guzzle6 guzzlehttp
1个回答
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;
  }
}

然后在代码中对所得的Prom调用->wait()

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

return array(
    'xmlAsJson' => $data
);
© www.soinside.com 2019 - 2024. All rights reserved.