Await for the completion of an async action.
516940
private void await() {
    try {
      // Clean up all filter join leaf nodes that have been converted
      boolean nodeRemoved = this.removeConvertedNodes(root);
      // If some nodes were removed, it means that we converted in the previous iteration
      // at least one filter join into a field data terms query. We don't have to wait since
      // we might have new filter join leaf nodes.
      if (!nodeRemoved && root.hasChildren()) {
        logger.debug("Visitor thread block - blocking queue size: {}", blockingQueue.size());
        this.blockingQueue.take();   // block until one async action is completed
        this.blockingQueue.offer(0); // add back the element to the queue, it will be removed after the node conversion
        logger.debug("Visitor thread unblock - blocking queue size: {}", blockingQueue.size());
      }
    }
    catch (InterruptedException e) {
      logger.warn("Filter join visitor thread interrupted while waiting");
      Thread.currentThread().interrupt();
    }
  }
328815
public void awaitSynchronous() {
    List<CompletableFuture<Void>> futures = pending.get();
    if (futures.isEmpty()) {
      return;
    }
    try {
      CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join();
    } catch (CompletionException e) {
      logger.log(Level.WARNING, null, e);
    } finally {
      futures.clear();
    }
  }
1052081
def _await_if_required(
        target: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]
    ) -> typing.Callable[..., typing.Any]:
        """"""

        @functools.wraps(target)
        def wrapper(*args, **kwargs):  # type: (typing.Any, typing.Any) -> typing.Any
            """Decorator/wrapper."""
            result = target(*args, **kwargs)
            if asyncio.iscoroutine(result):
                loop = asyncio.new_event_loop()
                result = loop.run_until_complete(result)
                loop.close()
            return result

        return wrapper
551225
function waitForCompletion(project) {
	return new Promise((resolve, reject) => {
		let warned = false;
		project.refreshUntilCompleted((completed, error) => {
			if (!error) {
				if (completed) {
					if (warned) {
						readLine.clearLine(process.stdout);  // clear "Waiting" line
						readLine.cursorTo(process.stdout, 0);  // move cursor to beginning of line
					}
					resolve();
				} else {
					if (!warned) {
						process.stdout.write("Waiting for " + project.name + " compilation to end ");
						warned = true;
					}
					process.stdout.write(".");
				}
			} else {
				reject(error);
			}
		});
	});
}
313435
private void awaitTasks() {
        if (_tasksPending.get() == 0) {
            return;
        }
        synchronized (this) {
            while (_tasksPending.get() != 0) {
                try {
                    logger.info("Scan tasks still pending, waiting");
                    wait();
                } catch (final InterruptedException e) {
                    logger.debug("Interrupted while awaiting task completion", e);
                }
            }
        }
    }
426192
async function waitForOperationSucceeded(config, result) {
    let count = 0;
    while (true) {
        let opResult = await new Operations().getOperationDetails({
            subscriptionKey: config.subscriptionKey,
            operationId: result.operationId
        });

        if (opResult.error)
            throw new Error(JSON.stringify(opResult.error, null, 4));

        result = await opResult.json();
        process.stderr.write(`'\r${result.operationState}`);
        count++;
        for (let x = 0; x < count; x++)
            process.stderr.write(`.`);
        process.stderr.write('              ');

        if (result.operationState === 'Failed')
            throw new Error(JSON.stringify(result, null, 4));

        if (result.operationState === 'Succeeded')
            break;
        await Delay(1000);
    }
    process.stderr.write('done\n');
    return result;
}
836973
public static <T> void completeFrom(CompletionStage<T> source, CompletableFuture<T> target) {
    source.whenComplete(
        (t, error) -> {
          if (error != null) {
            target.completeExceptionally(error);
          } else {
            target.complete(t);
          }
        });
  }
132241
void awaitRequests() {
        if (!isWaitingForEnriching()) {
            return;
        }
        for (int i = 0; i < NUMBER_OF_WAIT_LOOPS; i++) {
            try {
                Thread.sleep(THREAD_SLEEP);
                if (!isEnrichmentAdvertised()) {
                    return;
                }
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }
        throw new SettingRequestTimeoutException();
    }
747042
def context_completion_checker(async):
    """"""

    store_async_marker(async.id, async.result.status if async.result else -1)

    logging.debug("Async check completion for: %s", async.context_id)
    current_queue = _get_current_queue()
    from furious.async import Async
    logging.debug("Completion Check queue:%s", current_queue)
    Async(_completion_checker, queue=current_queue,
          args=(async.id, async.context_id)).start()

    return True
36782
@Override
    public void afterCompletion(int status) {
        if (status == Status.STATUS_COMMITTED) {
            Boolean previous = persistentExecutor.inMemoryTaskIds.put(taskId, Boolean.TRUE);
            if (previous == null) {
                long delay = expectedExecTime - new Date().getTime();
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(this, tc, "Schedule " + taskId + " for " + delay + "ms from now");
                persistentExecutor.scheduledExecutor.schedule(this, delay, TimeUnit.MILLISECONDS);
            } else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(this, tc, "Found task " + taskId + " already scheduled");
            }
        }
    }
533242
def StartAndWait(self):
        """"""
        self.StartTask()
        self.WaitUntilTaskDone(pydaq.DAQmx_Val_WaitInfinitely)
        self.ClearTask()
978898
public static Result onUiAsync(Action action) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            action.call();
            return new ActionAsyncTask(action, true);
        }
        ActionAsyncTask task = new ActionAsyncTask(action);
        getUiPoster().async(task);
        return task;
    }
1348690
public void complete( T result, Object error ) {
        synchronized (this) {
            if ( isComplete ) {
                throw new RuntimeException("Promise can be completed only once");
            }
            this.result = result;
            this.error = error;
            isComplete = true;
            tryFire();
        }
    }
584480
private <R, U> CompletionStage<U> doApplyToEitherAsync(
            CompletionStage<? extends R> first,
            CompletionStage<? extends R> second,
            Function<? super R, U> fn,
            Executor executor) {
    	CompletableCompletionStage<R> nextStage = newCompletableCompletionStage();

        // only the first result is accepted by completion stage,
        // the other one is ignored
        BiConsumer<R, Throwable> action = completeHandler(nextStage);
        first.whenComplete(action);
        second.whenComplete(action);

        return nextStage.thenApplyAsync(fn, executor);
    }
1293641
def _wait_for_async(conn, request_id):
    '''
    
    '''
    count = 0
    log.debug('Waiting for asynchronous operation to complete')
    result = conn.get_operation_status(request_id)
    while result.status == 'InProgress':
        count = count + 1
        if count > 120:
            raise ValueError('Timed out waiting for asynchronous operation to complete.')
        time.sleep(5)
        result = conn.get_operation_status(request_id)

    if result.status != 'Succeeded':
        raise AzureException('Operation failed. {message} ({code})'
                                .format(message=result.error.message,
                                        code=result.error.code))
766665
private <T> DeferredAction<M> deferAction(
      final M metadata, final Supplier<? extends CompletionStage<T>> action,
      final CompletableFuture<T> future
  ) {
    return new DeferredAction<>(metadata, () -> {
      final CompletionStage<? extends T> resultFuture;

      try {
        resultFuture = action.get();
      } catch (final Exception e) {
        future.completeExceptionally(e);
        markProcessed(metadata);
        return;
      }

      resultFuture.handleAsync((result, e) -> {
        if (e != null) {
          future.completeExceptionally(e);
        } else {
          future.complete(result);
        }

        markProcessed(metadata);
        return null;
      }, executor);
    });
  }
405669
final void postComplete() {
        /*
         * On each step, variable f holds current dependents to pop
         * and run.  It is extended along only one path at a time,
         * pushing others to avoid unbounded recursion.
         */
        CompletableFuture<?> f = this; Completion h;
        while ((h = f.stack) != null ||
               (f != this && (h = (f = this).stack) != null)) {
            CompletableFuture<?> d; Completion t;
            if (f.casStack(h, t = h.next)) {
                if (t != null) {
                    if (f != this) {
                        pushStack(h);
                        continue;
                    }
                    h.next = null;    // detach
                }
                f = (d = h.tryFire(NESTED)) == null ? this : d;
            }
        }
    }