55use React \SocketClient \ConnectorInterface ;
66use InvalidArgumentException ;
77use Exception ;
8+ use React \Promise \Promise ;
9+ use React \Promise \CancellablePromiseInterface ;
810
911class ConnectionManagerRepeat implements ConnectorInterface
1012{
@@ -27,16 +29,29 @@ public function create($host, $port)
2729
2830 public function tryConnection ($ repeat , $ host , $ port )
2931 {
30- $ that = $ this ;
31- return $ this ->connectionManager ->create ($ host , $ port )->then (
32- null ,
33- function ($ error ) use ($ repeat , $ that , $ host , $ port ) {
34- if ($ repeat > 0 ) {
35- return $ that ->tryConnection ($ repeat - 1 , $ host , $ port );
32+ $ tries = $ repeat + 1 ;
33+ $ connector = $ this ->connectionManager ;
34+
35+ return new Promise (function ($ resolve , $ reject ) use ($ host , $ port , &$ pending , &$ tries , $ connector ) {
36+ $ try = function ($ error = null ) use (&$ try , &$ pending , &$ tries , $ host , $ port , $ connector , $ resolve , $ reject ) {
37+ if ($ tries > 0 ) {
38+ --$ tries ;
39+ $ pending = $ connector ->create ($ host , $ port );
40+ $ pending ->then ($ resolve , $ try );
3641 } else {
37- throw new Exception ('Connection still fails even after repeating ' , 0 , $ error );
42+ $ reject ( new Exception ('Connection still fails even after repeating ' , 0 , $ error) );
3843 }
44+ };
45+
46+ $ try ();
47+ }, function ($ _ , $ reject ) use (&$ pending , &$ tries ) {
48+ // stop retrying, reject results and cancel pending attempt
49+ $ tries = 0 ;
50+ $ reject (new \RuntimeException ('Cancelled ' ));
51+
52+ if ($ pending instanceof CancellablePromiseInterface) {
53+ $ pending ->cancel ();
3954 }
40- );
55+ } );
4156 }
4257}
0 commit comments