我尝试在 SNS 客户端(适用于 PHP 的 AWS SDK)中使用 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');
但是当我想通过使用函数 createTopicAsync 来使用 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();
所以完整的 block 应该看起来像
$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:显然,以这种方式使用异步调用是有意义的。但要回答你的问题:为了在你的情况下得到任何结果,你应该同步强制你的 promise 完成,如上所述。
UPD2:在这里您可以看到an example of executing multiple async operations 。请注意,无论您有多少个 Promise,您都必须调用 wait()
关于php - 适用于 PHP 的 AWS 开发工具包中的 Promise 不起作用并且没有错误返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36416506/