AWS SDK中针对PHP的承诺不起作用,也不会返回错误


Promise in AWS SDK for PHP not work and no error return

我试图在SNS客户端(AWS SDK for PHP)中使用promise,但它不起作用。此代码(同步方式)与函数createTopic:配合使用

require 'aws/aws-autoloader.php';
use GuzzleHttp'Promise;
use Aws'Sns'SnsClient;
$client = new SnsClient([
    'version' => 'latest',
    'region'  => 'ap-northeast-1',
    'credentials' => [
        'key'    => 'xxx',
        'secret' => 'xxx',
    ],
]);
$result = $client->createTopic(['Name' => "test"]);
echo $result->get('TopicArn');

但是,当我想通过使用函数createTopicSync:来使用promise(异步方式)时

$result = $client->createTopicAsync(['Name' => "test"]);
$result->then(
    function ($value) {
        echo "The promise was fulfilled with {$value}";
    },
    function ($reason) {
        echo "The promise was rejected with {$reason}";
    }
);

它不起作用,什么也没发生,没有返回错误。有人知道可能出了什么问题吗?

尝试添加以下行:

// Wait for the operation to complete
$result->wait(); 

所以整个区块应该看起来像

$result = $client->createTopicAsync(['Name' => "test"]);
$result->then(
    function ($value) {
        echo "The promise was fulfilled with {$value}";
    },
    function ($reason) {
        echo "The promise was rejected with {$reason}";
    }
);
// Wait for the operation to complete
$result->wait(); 

UPD:显然,以这种方式使用异步调用有点道理。但为了回答你的问题:要想在你的案件中得到任何结果,你应该同步地迫使你的承诺按照上述方式完成。

UPD2:这里可以看到执行多个异步操作的示例。请注意,不管您有多少承诺,您都必须调用wait()