Wait for another callback to occur before continuing

@param {string|string[]|Store} token - The collection of dispatch tokens to wait on
769644
function (token) {
    var tokens = token;
    if (!_.isArray(tokens)) {
      tokens = [tokens];
    }

    tokens = tokens.map(function (token) {
      // Allow passing stores straight and we grab the dispatcherToken
      return token.dispatcherToken || token;
    });

    return this.dispatcher.waitFor(tokens);
  }
1057170
function whenReady() {
    var pendingObjects = [].slice.call(arguments),
        wait = pendingObjects.length,
        resolvedCallback,
        promise = {
            run : function (callback) {
                resolvedCallback = callback;
            }
        },
        resolved = function () {
            wait -= 1;
            if (wait <= 0 && resolvedCallback) {
                resolvedCallback();
            }
        },
        i;

    for (i = 0; i < pendingObjects.length; i++) {
        if (typeof pendingObjects[i].onReady === 'function') {
            pendingObjects[i].onReady(resolved);
        } else {
            window.setTimeout(resolved, 0);
        }
    }
    if (pendingObjects.length === 0) {
        window.setTimeout(resolved, 0);
    }

    return promise; // to Domenic, this is not a promise, I know :).
}
433425
function waitFor(check, cb, params) {
    params = params || {};
    if (typeof cb === 'object') {
      params = cb;
      cb = params.done;
    }

    var milliseconds = params.interval || 30,
        j = 0;

    var i = setInterval(function() {
      if (check()) {
        clearInterval(i);
        cb(null);
      }

      if (params.timeout && params.timeout - (j * milliseconds) <= 0) {
        clearInterval(i);
        cb(new Error('timeout'));
      }

      j++;
    }, milliseconds);
  }
1229634
function(err) {
        if (err) this._onError(err);
        if (this._continueErrors || !err) {
            var args = [].slice.call(arguments);
            if (this._callbacks.length > 0) {
                this._isQueueRunning = true;
                var cb = this._callbacks.shift();
                cb = cb.bind(this);
                args = args.slice(1);
                args.push(this.next);
                cb.apply(this, args);

            } else {
                this._isQueueRunning = false;
                this.start = (function() {
                    this.start = null;
                    this.next.apply(this, args);
                }).bind(this);

            }
        }
        return this;
    }
605973
function(callback) {
        if (res.parsedHeader.payload.mode === 'handshake') {
          res.session = {
            sid: reqSid,
            cert: senderCert,
            token: reqToken
          };
          callback(null);
        } else {
          var querySid;
          if (sessionStore instanceof Store || 'undefined' !== typeof window) {
            querySid = my.config.urlBase;
          } else {
            querySid = reqSid;
          }
          // load the session if exists
          sessionStore.load(querySid, function(err, session){
            if (err) {
              callback(err);
            } else if (session) {
              log.debug('%s loaded session', app.name);
              log.debug(session);
              res.session = session;
              callback(null);
            } else {
              callback('session expired');
            }
          });
        }
      }
501404
function onsuccess(event) {
            // remember the db instance
            self.db = event.target.result;

            // storage is now possible
            self.store = true;

            // execute all pending operations
            while (self.waiting.length) {
                self.waiting.shift().call(self);
            }

            // we're done, fire the callback
            if (cb) {
                cb.call(self, self);
            }
        }
89206
public void push(T token) {
        if (token == lastPushed) return;
        lastPushed = token;
        if (token.getChannel() == TokenChannel.Default) {
            main.add(token);
        }
        all.add(token);
    }
977000
function(){
		var me = this,
			dispatchArguments = arguments,
			promises = []
		;

		this._promises = [];

		// A closure is needed for the callback id
		Object.keys( this._callbacks ).forEach( function( id ){

			// All the promises must be set in me._promises before trying to resolve
			// in order to make waitFor work ok
			me._promises[ id ] = me._Promise.resolve()
				.then( function(){
					return me._callbacks[ id ].apply( me, dispatchArguments );
				})
				.catch( function( err ){
					console.error( err.stack || err );
				})
			;

			promises.push( me._promises[ id ] );
		});

		//
		var dequeue = function(){
			me._dispatchQueue.shift();
			if( !me._dispatchQueue.length )
				me._currentDispatch = false;
		};

		return this._Promise.all( promises )
			.then( dequeue, dequeue )
		;
	}
158195
function wait(testCallback, waitCallback) {
          if (!testCallback()) {
            // Wait for timeout
            if ((new Date().getTime()) - startTime < maxLoadTime) {
              Delay.setTimeout(waitCallback);
            } else {
              failed();
            }
          }
        }
484945
function CheckTokens(callback, token_fetch)
	{
		// build list of tokens we're missing
		var todo = [];

		// force token_fetch to an array
		token_fetch = [].concat(token_fetch);

		// make sure we're actually logged in first
		if (!auth_obj.auth_code)
		{
			Log("Need to login - no auth token found");
			todo.push({name: "Login", func: Login});
		}

		if (!auth_obj.expire_time || auth_obj.expire_time < new Date().getTime())
		{
			// token has expired! Fetch access_token again
			Log("Need to fetch access tokens - tokens expired");
			todo.push({name: "GetAccessToken", func: GetAccessToken});
		}
		else if (!auth_obj.access_token)
		{
			// we have no access token (?!)
			Log("Need to fetch access tokens - no token available");
			todo.push({name: "GetAccessToken", func: GetAccessToken});
		}

		if (!auth_obj.username || !auth_obj.region)
		{
			// missing player username/region
			Log("Need to fetch userdata - no region or username available");
			todo.push({name: "GetUserData", func: GetUserData});
		}

		if (todo.length == 0)
		{
			// everything is fine
			if (callback) callback(false);
		}
		else
		{
			// work through our list of tokens we need to update
			var step = function()
			{
				var func = todo.shift();
				if (!func)
				{
					// all done!
					if (callback) callback(false);
					return;
				}

				if (token_fetch.indexOf(func.func) >= 0)
				{
					// if we're actually calling a token fetch function, skip!
					process.nextTick(step);
				}
				else
				{
					func.func(function(error) {
						if (error)
						{
							// token fetching error!
							if (callback) callback(func.name + " :: " + error);
							return;
						}

						// do next step
						process.nextTick(step);
					});
				}
			};

			// start updating tokens
			process.nextTick(step);
		}
	}
504939
function waitForCancel() {
  /* jshint validthis: true */
  var self = this;
  var cancel_batch = {};
  cancel_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true;
  self.call.startBatch(cancel_batch, function(err, result) {
    if (err) {
      self.emit('error', err);
    }
    if (result.cancelled) {
      self.cancelled = true;
      self.emit('cancelled');
    }
  });
}
131087
function processTokens(tokens, callback) {
    "use strict";
    var processFunctions = underscore.map(tokens, function (word) {
        return function (cb) {
            tokenizeWord(word, cb);
        };
    });
    async.parallel(
        processFunctions,
        function (error, results) {
            if (error) {
                callback(error, null);
            } else {
                var normalizedTokens = [];
                results.forEach(function (tokens) {
                    normalizedTokens = normalizedTokens.concat(tokens);
                });
                normalizedTokens.sort();
                normalizedTokens = underscore.uniq(normalizedTokens, true);
                callback(null, normalizedTokens);
            }
        }
    );
}
163854
def waitforcard(self):
        """"""
        AbstractCardRequest.waitforcard(self)
        cardfound = False

        # for non infinite timeout, a timer will signal
        # the end of the time-out by setting the evt event
        evt = threading.Event()
        if INFINITE == self.timeout:
            timertimeout = 1
        else:
            timertimeout = self.timeout
        timer = threading.Timer(
            timertimeout, signalEvent, [evt, INFINITE == self.timeout])

        # create a dictionary entry for new readers
        readerstates = {}
        readernames = self.getReaderNames()
        for reader in readernames:
            if not reader in readerstates:
                readerstates[reader] = (reader, SCARD_STATE_UNAWARE)

        # remove dictionary entry for readers that disappeared
        for oldreader in list(readerstates.keys()):
            if oldreader not in readernames:
                del readerstates[oldreader]

        # call SCardGetStatusChange only if we have some readers
        if {} != readerstates:
            hresult, newstates = SCardGetStatusChange(
                self.hcontext, 0, list(readerstates.values()))
        else:
            hresult = 0
            newstates = []

        # we can expect normally time-outs or reader
        # disappearing just before the call
        # otherwise, raise execption on error
        if 0 != hresult and \
            SCARD_E_TIMEOUT != hresult and \
            SCARD_E_UNKNOWN_READER != hresult:
                raise CardRequestException(
                    'Failed to SCardGetStatusChange ' + \
                    SCardGetErrorMessage(hresult))

        # in case of timeout or reader disappearing,
        # the content of the states is useless
        # in which case we clear the changed bit
        if SCARD_E_TIMEOUT == hresult or SCARD_E_UNKNOWN_READER == hresult:
            for state in newstates:
                state[1] = state[1] & (0xFFFFFFFF ^ SCARD_STATE_CHANGED)

        # update readerstate
        for state in newstates:
            readername, eventstate, atr = state
            readerstates[readername] = (readername, eventstate)

        # if a new card is not requested, just return the first available
        if not self.newcardonly:
            for state in newstates:
                readername, eventstate, atr = state
                if eventstate & SCARD_STATE_PRESENT:
                    reader = PCSCReader(readername)
                    if self.cardType.matches(atr, reader):
                        if self.cardServiceClass.supports('dummy'):
                            cardfound = True
                            return self.cardServiceClass(
                                    reader.createConnection())

        timerstarted = False
        while not evt.isSet() and not cardfound:

            if not timerstarted:
                timerstarted = True
                timer.start()

            time.sleep(self.pollinginterval)

            # create a dictionary entry for new readers
            readernames = self.getReaderNames()
            for reader in readernames:
                if not reader in readerstates:
                    readerstates[reader] = (reader, SCARD_STATE_UNAWARE)

            # remove dictionary entry for readers that disappeared
            for oldreader in list(readerstates.keys()):
                if oldreader not in readernames:
                    del readerstates[oldreader]

            # wait for card insertion
            if {} != readerstates:
                hresult, newstates = SCardGetStatusChange(
                    self.hcontext, 0, list(readerstates.values()))
            else:
                hresult = SCARD_E_TIMEOUT
                newstates = []

            # time-out
            if SCARD_E_TIMEOUT == hresult:
                if evt.isSet():
                    raise CardRequestTimeoutException()

            # reader vanished before or during the call
            elif SCARD_E_UNKNOWN_READER == hresult:
                pass

            # some error happened
            elif 0 != hresult:
                timer.cancel()
                raise CardRequestException(
                    'Failed to get status change ' + \
                    SCardGetErrorMessage(hresult))

            # something changed!
            else:

                # check if we have to return a match, i.e.
                # if no new card in inserted and there is a card found
                # or if a new card is requested, and there is a change+present
                for state in newstates:
                    readername, eventstate, atr = state
                    r, oldstate = readerstates[readername]

                    # the status can change on a card already inserted, e.g.
                    # unpowered, in use, ...
                    # if a new card is requested, clear the state changed bit
                    # if the card was already inserted and is still inserted
                    if self.newcardonly:
                        if oldstate & SCARD_STATE_PRESENT and \
                            eventstate & \
                                (SCARD_STATE_CHANGED | SCARD_STATE_PRESENT):
                            eventstate = eventstate & \
                                (0xFFFFFFFF ^ SCARD_STATE_CHANGED)

                    if (self.newcardonly and \
                            eventstate & SCARD_STATE_PRESENT and \
                            eventstate & SCARD_STATE_CHANGED) or \
                        (not self.newcardonly and \
                         eventstate & SCARD_STATE_PRESENT):
                        reader = PCSCReader(readername)
                        if self.cardType.matches(atr, reader):
                            if self.cardServiceClass.supports('dummy'):
                                cardfound = True
                                timer.cancel()
                                return self.cardServiceClass(
                                        reader.createConnection())

                    # update state dictionary
                    readerstates[readername] = (readername, eventstate)

            if evt.isSet():
                raise CardRequestTimeoutException()
333172
void waitRun(long waitMillis, int waitNanos, boolean cancelOnTimeOut) {
        if (!mDone) {
            synchronized (this) {
                if (!mDone) {
                    try {
                        this.wait(waitMillis, waitNanos);
                    } catch (InterruptedException ignored) {
                    } finally {
                        if (!mDone && cancelOnTimeOut)
                            mDone = true;
                    }
                }
            }
        }
    }
148981
private void waitForCallback(final String uuid, final long timeout) throws TimeoutException {

		synchronized (lock) {

			this.message = null;
			this.hasTimeout = true;

			try {
				lock.wait(timeout);

			} catch (InterruptedException iex) {
				logger.warn("", iex);
			}

			// remove timed out callback
			if (this.hasTimeout) {

				peer.unregisterCallback(uuid);
				throw new TimeoutException();
			}
		}
	}
930231
function(callback) {

    if (typeof this.publisher !== 'function') {
      var pubErrMsg = 'publisher not injected!';
      debug(pubErrMsg);
      if (callback) callback(new Error(pubErrMsg));
      return;
    }

    if (!this.store || typeof this.store.getUndispatchedEvents !== 'function'
                    || typeof this.store.setEventToDispatched !== 'function') {
      var storeErrMsg = 'store not injected!';
      debug(storeErrMsg);
      if (callback) callback(new Error(storeErrMsg))
      return;
    }

    var self = this;

    // Get all undispatched events from store and queue them
    // before all other events passed in by the addUndispatchedEvents function.
    this.store.getUndispatchedEvents(function(err, events) {

      if (err) {
        debug(err);
        if (callback) callback(err);
        return;
      }

      var triggered = false;
      if (events) {
        for (var i = 0, len = events.length; i < len; i++) {
          self.undispatchedEventsQueue.push(events[i]);
          // If there are a lot of events then we can hit issues with the call stack size when processing in one go
          triggered = false;
          if (i % 1000 === 0){
            triggered = true;
            trigger(self);
          }
        }
      }

      if (!triggered) {
        trigger(self);
      }

      if (callback) callback(null);
    });
  }
1020016
function (callback) {
      var trace = new Error(this.constructor.name + ': dispatcher handler error');
      var token = this.dispatcher.register(this.catchError(callback, trace));
      this.tokens.push(token);
    }