【问题标题】:How to wait for promise to complete in another class如何等待承诺在另一个班级完成
【发布时间】:2020-05-26 01:51:57
【问题描述】:

在另一堂课上,我有一个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。

【问题讨论】:

    标签: php guzzle6 guzzle


    【解决方案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;
      }
    }
    

    稍后在代码中调用 ->wait() 生成的承诺:

    $data = ( new PromiseController )->load()->wait();
    
    return array(
        'xmlAsJson' => $data
    );
    

    【讨论】:

    • 太棒了,伙计!!
    猜你喜欢
    • 1970-01-01
    • 2016-10-16
    • 2017-06-17
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多