5353function await (PromiseInterface $ promise )
5454{
5555 $ wait = true ;
56- $ resolved = null ;
57- $ exception = null ;
56+ $ resolved = false ;
5857 $ rejected = false ;
58+ $ resolvedValue = null ;
59+ $ rejectedThrowable = null ;
5960
6061 $ promise ->then (
61- function ($ c ) use (&$ resolved , &$ wait ) {
62- $ resolved = $ c ;
62+ function ($ c ) use (&$ resolved , &$ resolvedValue , &$ wait ) {
63+ $ resolvedValue = $ c ;
64+ $ resolved = true ;
6365 $ wait = false ;
6466 Loop::stop ();
6567 },
66- function ($ error ) use (&$ exception , &$ rejected , &$ wait ) {
67- $ exception = $ error ;
68+ function ($ error ) use (&$ rejected , &$ rejectedThrowable , &$ wait ) {
69+ $ rejectedThrowable = $ error ;
6870 $ rejected = true ;
6971 $ wait = false ;
7072 Loop::stop ();
@@ -75,24 +77,44 @@ function ($error) use (&$exception, &$rejected, &$wait) {
7577 // argument does not show up in the stack trace in PHP 7+ only.
7678 $ promise = null ;
7779
80+ if ($ rejected ) {
81+ awaitThrow ($ rejectedThrowable );
82+ }
83+
84+ if ($ resolved ) {
85+ return $ resolvedValue ;
86+ }
87+
7888 while ($ wait ) {
7989 Loop::run ();
8090 }
8191
8292 if ($ rejected ) {
83- // promise is rejected with an unexpected value (Promise API v1 or v2 only)
84- if (!$ exception instanceof \Throwable) {
85- $ exception = new \UnexpectedValueException (
86- 'Promise rejected with unexpected value of type ' . (is_object ($ exception ) ? get_class ($ exception ) : gettype ($ exception ))
87- );
88- }
89-
90- throw $ exception ;
93+ awaitThrow ($ rejectedThrowable );
9194 }
9295
93- return $ resolved ;
96+ return $ resolvedValue ;
9497}
9598
99+ /**
100+ * This function is for internal use only. But it wraps the data a promise is rejected with in a \UnexpectedValueException
101+ * when it isn't an \Exception or a \Throwable.
102+ *
103+ * @internal
104+ * @param \Exception|\Throwable $rejectedThrowable
105+ * @throws \Exception|\Throwable
106+ */
107+ function awaitThrow ($ rejectedThrowable )
108+ {
109+ // promise is rejected with an unexpected value (Promise API v1 or v2 only)
110+ if (!$ rejectedThrowable instanceof \Exception && !$ rejectedThrowable instanceof \Throwable) {
111+ $ rejectedThrowable = new \UnexpectedValueException (
112+ 'Promise rejected with unexpected value of type ' . (is_object ($ rejectedThrowable ) ? get_class ($ rejectedThrowable ) : gettype ($ rejectedThrowable ))
113+ );
114+ }
115+
116+ throw $ rejectedThrowable ;
117+ }
96118
97119/**
98120 * Execute a Generator-based coroutine to "await" promises.
0 commit comments