停止foreach循环的麻烦取决于承诺解决或拒绝

问题描述 投票:0回答:1
$msg_sent = false;
foreach ($channels as $channel) {
    $resolve = function() use ( &$msg_sent )
    {
        $msg_sent = true;
    };
    $reject = function( \Exception $e )
    {
        error_log( $e, 3, './error.txt' . PHP_EOL );
    };
    $channel->send('hlw')->done( $resolve, $reject );
    if ( $msg_sent ){
        break;
    } else {
        continue;
    }
}

如上所示, $ msg_sent是假的, $ channels是一个包含3个相同对象实例的数组(具有不同的值) 当我点击send()时,它返回一个ExtendedPromiseInterface,其中$ resolve在发送消息时执行,$ reject在未发送时执行。

所以我想做的是检查消息是否被发送,如果没有,则继续循环并尝试将消息发送到另一个通道,如果发送则打破循环。

但出乎意料的是,它总是返回false,即使发送了消息,循环也会运行。

php asynchronous promise reactphp
1个回答
0
投票

嘿ReactPHP团队成员在这里。那个foreach循环只会(几乎)同时发送所有内容。您可以执行类似这样的操作,仅在您收到前一个请求(伪代码)之后发送请求,该请求在成功时解析为true,在所有调用失败时解析为false:

final class Bier
{
    public function check($channels): PromiseInterface
    {
        $channel = array_shift($channels);
        return $channel->send('hlw')->then(function () {
            return resolve(true);
        }, function () use ($channels) {
            if (count($channels) === 0) {
                return resolve(false);
            }
            return resolve($this->check($channels));
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.