44
55use React \SocketClient \ConnectorInterface ;
66use React \EventLoop \LoopInterface ;
7- use React \Promise \Deferred ;
7+ use React \Promise \Timer ;
88use Exception ;
99
1010class ConnectionManagerTimeout implements ConnectorInterface
@@ -22,28 +22,15 @@ public function __construct(ConnectorInterface $connectionManager, LoopInterface
2222
2323 public function create ($ host , $ port )
2424 {
25- $ deferred = new Deferred ();
26- $ timedout = false ;
25+ $ promise = $ this ->connectionManager ->create ($ host , $ port );
2726
28- $ tid = $ this ->loop ->addTimer ($ this ->timeout , function () use ($ deferred , &$ timedout ) {
29- $ deferred ->reject (new Exception ('Connection attempt timed out ' ));
30- $ timedout = true ;
31- // TODO: find a proper way to actually cancel the connection
32- });
33-
34- $ loop = $ this ->loop ;
35- $ this ->connectionManager ->create ($ host , $ port )->then (function ($ connection ) use ($ tid , $ loop , &$ timedout , $ deferred ) {
36- if ($ timedout ) {
37- // connection successfully established but timeout already expired => close successful connection
27+ return Timer \timeout ($ promise , $ this ->timeout , $ this ->loop )->then (null , function ($ e ) use ($ promise ) {
28+ // connection successfully established but timeout already expired => close successful connection
29+ $ promise ->then (function ($ connection ) {
3830 $ connection ->end ();
39- } else {
40- $ loop ->cancelTimer ($ tid );
41- $ deferred ->resolve ($ connection );
42- }
43- }, function ($ error ) use ($ loop , $ tid , $ deferred ) {
44- $ loop ->cancelTimer ($ tid );
45- $ deferred ->reject ($ error );
31+ });
32+
33+ throw $ e ;
4634 });
47- return $ deferred ->promise ();
4835 }
4936}
0 commit comments