@@ -239,21 +239,55 @@ protected function getPromiseAdapter()
239239 */
240240 public static function await ($ promise = null , $ unwrap = true )
241241 {
242+ self ::awaitInstances ();
243+
244+ if (null === $ promise ) {
245+ return null ;
246+ }
247+
248+ if (is_callable ([$ promise , 'then ' ])) {
249+ $ isPromiseCompleted = false ;
250+ $ resolvedValue = null ;
251+ $ rejectedReason = null ;
252+
253+ $ promise ->then (
254+ function ($ value ) use (&$ isPromiseCompleted , &$ resolvedValue ) {
255+ $ isPromiseCompleted = true ;
256+ $ resolvedValue = $ value ;
257+ },
258+ function ($ reason ) use (&$ isPromiseCompleted , &$ rejectedReason ) {
259+ $ isPromiseCompleted = true ;
260+ $ rejectedReason = $ reason ;
261+ }
262+ );
263+
264+ //Promise is completed?
265+ if ($ isPromiseCompleted ) {
266+ // rejected ?
267+ if ($ rejectedReason instanceof \Exception) {
268+ if (!$ unwrap ) {
269+ return $ rejectedReason ;
270+ }
271+ throw $ rejectedReason ;
272+ }
273+
274+ return $ resolvedValue ;
275+ }
276+ }
277+
242278 if (empty (self ::$ instances )) {
243279 throw new \RuntimeException ('Found no active DataLoader instance. ' );
244280 }
245- self ::awaitInstances ();
246281
247282 return self ::$ instances [0 ]->getPromiseAdapter ()->await ($ promise , $ unwrap );
248283 }
249284
250285 private static function awaitInstances ()
251286 {
252- $ dataLoaders = self ::$ instances ;
287+ do {
288+ $ wait = false ;
289+ $ dataLoaders = self ::$ instances ;
253290
254- $ wait = true ;
255-
256- while ($ wait ) {
257291 foreach ($ dataLoaders as $ dataLoader ) {
258292 if (!$ dataLoader || !$ dataLoader ->needProcess ()) {
259293 $ wait = false ;
@@ -262,12 +296,7 @@ private static function awaitInstances()
262296 $ wait = true ;
263297 $ dataLoader ->process ();
264298 }
265- }
266-
267- // If new dataloaders were instanciated in the meantime, wait again !
268- if (count ($ dataLoaders ) != count (self ::$ instances )) {
269- self ::awaitInstances ();
270- }
299+ } while ($ wait );
271300 }
272301
273302 /**
0 commit comments