Blocks until the intial async query finishes. After this call either .rows or .error will be non-nil.

TODO: It seems that implementation of waitForRows() is not correct. Should fix this!!!
https://github.com/couchbase/couchbase-lite-java-core/issues/647
427546
@InterfaceAudience.Public
    public void waitForRows() throws CouchbaseLiteException {
        start();

        while (true) {
            try {
                queryFuture.get();
                break;
            } catch (InterruptedException e) {
                continue;
            } catch (Exception e) {
                lastError = e;
                throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
            }
        }
    }
7496
public void waitInitOpen(String waitForSelector) {
        if (waitForSelector == null || waitForSelector.isEmpty()) {
            initDynamic();
            open();
            return;
        }
        waitInitOpen(waitForSelector, getElement());
    }
1274083
def executeAndWait(self, query, clientCtx):
    
    self.send_executeAndWait(query, clientCtx)
    return self.recv_executeAndWait()
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();
    }
  }
456030
private void sequenceQuery(QueryEntry entry, CompletableFuture<QueryResponse> future) {
    // Get the client's server session. If the session doesn't exist, return an unknown session error.
    ServerSessionContext session = context.getStateMachine().executor().context().sessions().getSession(entry.getSession());
    if (session == null) {
      future.complete(logResponse(QueryResponse.builder()
        .withStatus(Response.Status.ERROR)
        .withError(CopycatError.Type.UNKNOWN_SESSION_ERROR)
        .build()));
    } else {
      sequenceQuery(entry, session, future);
    }
  }
714789
function (timeout, hash, uuid) {
    this.actionQueue.push(this.webdriverClient.implicitWait.bind(this.webdriverClient, timeout));
    this.actionQueue.push(this._waitCb.bind(this, timeout, hash, uuid));
    return this;
  }
122209
@Override
    public List<QueryRow> regularQuery(final QueryOptions options) throws CouchbaseLiteException {

        final Predicate<QueryRow> postFilter = options.getPostFilter();

        int tmpLimit = QueryOptions.QUERY_OPTIONS_DEFAULT_LIMIT;
        int tmpSkip = 0;
        if (postFilter != null) {
            // #574: Custom post-filter means skip/limit apply to the filtered rows, not to the
            // underlying query, so handle them specially:
            tmpLimit = options.getLimit();
            tmpSkip = options.getSkip();
            if (tmpLimit == 0)
                return new ArrayList<QueryRow>(); // empty result set
            options.setLimit(QueryOptions.QUERY_OPTIONS_DEFAULT_LIMIT);
            options.setSkip(0);
        }

        final CountDown skip = new CountDown(tmpSkip);
        final CountDown limit = new CountDown(tmpLimit);

        final List<QueryRow> rows = new ArrayList<QueryRow>();

        Status status = runQuery(options, new QueryRowBlock() {
            @Override
            public Status onRow(byte[] keyData, byte[] valueData, String docID, Cursor cursor) {
                JsonDocument keyDoc = new JsonDocument(keyData);
                JsonDocument valueDoc = new JsonDocument(valueData);
                long sequence = Long.parseLong(cursor.getString(3));
                RevisionInternal docRevision = null;
                if (options.isIncludeDocs()) {
                    Object valueObject = valueDoc.jsonObject();
                    String linkedID = null;
                    if (valueObject instanceof Map)
                        linkedID = (String) ((Map) valueObject).get("_id");
                    if (linkedID != null) {
                        // Linked document: http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Linked_documents
                        String linkedRev = (String) ((Map) valueObject).get("_rev");
                        Status linkedStatus = new Status();
                        docRevision = store.getDocument(linkedID, linkedRev, true, linkedStatus);
                        sequence = docRevision.getSequence();
                    } else {
                        String revID = cursor.getString(4);
                        byte[] json = cursor.getBlob(5);
                        Map<String, Object> properties = store.documentPropertiesFromJSON(
                                json,
                                docID,
                                revID,
                                false,
                                sequence);
                        docRevision = SQLiteStore.revision(
                                docID,    // docID
                                revID,    // revID
                                false,    // deleted
                                sequence, // sequence
                                properties// properties
                        );
                    }
                }
                QueryRow row = new QueryRow(docID, sequence,
                        keyDoc.jsonObject(), valueDoc.jsonObject(),
                        docRevision);
                if (postFilter != null) {
                    if (!postFilter.apply(row)) {
                        return new Status(Status.OK);
                    }
                    if (skip.getCount() > 0) {
                        skip.countDown();
                        return new Status(Status.OK);
                    }

                }
                rows.add(row);

                if (limit.countDown() == 0)
                    return new Status(0); /// stops the iteration
                return new Status(Status.OK);
            }
        });

        // If given keys, sort the output into that order, and add entries for missing keys:
        if (options.getKeys() != null && options.getKeys().size() > 0) {
            // Group rows by key:
            Map<Object, List<QueryRow>> rowsByKey = new HashMap<Object, List<QueryRow>>();
            for (QueryRow row : rows) {
                List<QueryRow> rs = rowsByKey.get(row.getKey());
                if (rs == null) {
                    rs = new ArrayList<QueryRow>();
                    rowsByKey.put(row.getKey(), rs);
                }
                rs.add(row);
            }

            // Now concatenate them in the order the keys are given in options:
            final List<QueryRow> sortedRows = new ArrayList<QueryRow>();
            for (Object key : options.getKeys()) {
                JsonDocument jsonDoc = null;
                try {
                    byte[] keyBytes = Manager.getObjectMapper().writeValueAsBytes(key);
                    jsonDoc = new JsonDocument(keyBytes);
                } catch (JsonProcessingException e) {
                    throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
                }
                List<QueryRow> rs = rowsByKey.get(jsonDoc.jsonObject());
                if (rs != null)
                    sortedRows.addAll(rs);
            }

            return sortedRows;
        }

        return rows;
    }
533379
public void waitUntilComplete() {
        lock.lock();
        try {
            while(processing || count.get() > 0) {
                try {
                    processing_done.await();
                }
                catch(InterruptedException ignored) {
                }
            }
        }
        finally {
            lock.unlock();
        }
    }
656327
async function executeAthenaQuery (athena, request, logging) {
	let getResultsParams = await startQuery(athena, request, logging);
	if (getResultsParams) {
		let data;
		let previousToken = null;
		do {
			if ((data) && (data.NextToken) && (data.NextToken !== previousToken)) {
				previousToken = data.NextToken;
				getResultsParams.NextToken = data.NextToken;
			}
			data = await getResults(athena, getResultsParams, request, logging);
			if (request.isFormatJson()) {
		 		outputJson(data, request.getOutput());
			} else {
		 		outputRaw(data, request.getOutput());
			}
		} while ((data) && (data.NextToken) && (data.NextToken !== previousToken));	
	}
}
284405
public void waitForJoiningHostsToBeReady(int expectedHosts, int localHostId) {
        try {
            //register this host as joining. The host registration will be deleted after joining is completed.
            m_zk.create(ZKUtil.joinZKPath(CoreZK.readyjoininghosts, Integer.toString(localHostId)) , null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            while (true) {
                ZKUtil.FutureWatcher fw = new ZKUtil.FutureWatcher();
                int readyHosts = m_zk.getChildren(CoreZK.readyjoininghosts, fw).size();
                if ( readyHosts == expectedHosts) {
                    break;
                }
                fw.get();
            }
        } catch (KeeperException | InterruptedException e) {
            org.voltdb.VoltDB.crashLocalVoltDB("Error waiting for hosts to be ready", false, e);
        }
    }
137139
function delayedQuerySearch(criteria) {
      if (!pendingSearch || !debounceSearch())  {
        cancelSearch();

        return pendingSearch = $q(function(resolve, reject) {
          // Simulate async search... (after debouncing)
          cancelSearch = reject;
          $timeout(function() {

            resolve(self.querySearch(criteria));

            refreshDebounce();
          }, Math.random() * 500, true);
        });
      }

      return pendingSearch;
    }
292728
function waitForChildCallback (parent, predicate, callback) {
  if (predicate(parent)) {
    callback()

    return
  }

  const win = parent.ownerDocument.defaultView

  if (win.MutationObserver) {
    /**
     * @type {!MutationObserver}
     */
    const observer = new win.MutationObserver(() => {
      if (predicate(parent)) {
        observer.disconnect()
        callback()
      }
    })

    observer.observe(parent, {childList: true})

    return
  }

  const intervalId = win.setInterval(() => {
    if (predicate(parent)) {
      win.clearInterval(intervalId)
      callback()
    }
  }, 5)
}
148681
public void waitForCompletion() throws InterruptedException {
        try {
            waitForCompletion(0L);
        } catch (AsyncTimeoutException ate) {
            // cannot happen since arg of 0L means wait forever
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Unexpected timeout on blocking wait call, exception: " + ate.getMessage());
            }
            FFDCFilter.processException(ate,
                                        getClass().getName() + ".waitForCompletion", "268", this);
            InterruptedException ie = new InterruptedException("Unexpected timeout");
            ie.initCause(ate);
            throw ie;
        }
    }
607334
@Override
    public void waitForFinish() throws IOException
    {
        if (future == null)
        {
            throw new IllegalStateException("not started");
        }
        try
        {
            future.get();
        }
        catch (InterruptedException | ExecutionException ex)
        {
            throw new IOException(ex);
        }
    }
391564
private void runQuery() {
		if(this.rowKeysList != null && this.rowKeysList.size() > 0) { // Check if there are rowkeys to query Cassandra
			if (threadCount > 1) { // When thread count greater than 1 enables parallelism, use threads to query Cassandra
				// multiple times
				
				ExecutorService executor = Executors
						.newFixedThreadPool(threadCount);
				List<Future<?>> futures = new LinkedList<Future<?>>();

				for (final List<K> param : this.rowKeysList) {
					Future<?> future = executor.submit(new Runnable() {
						public void run() {
							// Query Cassandra with the input keys provided
							runMultigetSliceQuery(param); 
							
						}
					});

					futures.add(future);
				}

				for (Future<?> f : futures) {// iterate through thread results
					try {
						f.get(); // wait for thread to complete

					} catch (InterruptedException e) {
						throw new HectorException("Failed to retrieve rows from Cassandra.",e);
					} 
					catch (ExecutionException e) {
						throw new HectorException("Failed to retrieve rows from Cassandra.",e);
					} 
				}
				// Safe to shutdown the threadpool and release the resources
				executor.shutdown(); 

				// set the rowKeysIndex to size of input keys so as no further calls
				// will be made to Cassandra.
				// This ensures iterator.hasNext() returns false when all keys are
				// queried
				rowKeysIndex = this.rowKeysList.size();

			}
			else {// When thread count less than or equal to 1 (0 or negative) disables
				// parallelism, set of(maxRowCountPerQuery) keys queries
				// Cassandra at a time
			
				runMultigetSliceQuery(this.rowKeysList.get(rowKeysIndex));
				// Increment the rowKeyIndex instead of setting it to  this.rowKeysList.size(); 
				rowKeysIndex++; 
				
			}
		}

		ArrayList<Row<K, N, V>> resultList = new ArrayList<Row<K, N, V>>(queryResult.size());

		synchronized (queryResult) {
			// Ensure that runMultigetSliceQuery() method call updates global
			// variable queryResult with query result (if exists)
			if (queryResult != null && queryResult.size() > 0)	{
				for (Rows<K, N, V> rows : queryResult) {
					if (rows != null && rows.getCount() > 0) {
						for (Row<K, N, V> row : rows) {
							// prepare List<Row<K, N, V>> to return
							// the iterator of <Row<K,N,V>> to the caller
							resultList.add(row);
						}
					}

				}
			}
		}

		// assign global iterator with the result of multigetSliceQuery
		iterator = resultList.iterator(); 
										

	}
78269
def wait_nonblock(method, *args)
      loop do
        result = __send__(method, *args, exception: false)
        case result
          when :wait_readable
            io_watcher.wait_readable
          when :wait_writable
            io_watcher.wait_writable
          else
            return result
        end
      end
    end
581761
def wait_for(self, predicate, timeout=None):
        
        if not is_locked(self._lock):
            raise RuntimeError('lock is not locked')
        hub = get_hub()
        try:
            with switch_back(timeout, lock=thread_lock(self._lock)) as switcher:
                handle = add_callback(self, switcher, predicate)
                # See the comment in Lock.acquire() why it is OK to release the
                # lock here before calling hub.switch().
                # Also if this is a reentrant lock make sure it is fully released.
                state = release_save(self._lock)
                hub.switch()
        except BaseException as e:
            with self._lock:
                remove_callback(self, handle)
            if e is switcher.timeout:
                return False
            raise
        finally:
            acquire_restore(self._lock, state)
        return True