Async Helpers
--------------

Some helpful functions to deal with asynchronous matters.
 Waiting for something to happen
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);
  }
578743
def wait(self, method, *args):
        
        methodargs = encode_args(args, extra=True)
        js = """
        %s(%s wait_callback);
        """ % (method, methodargs)
        self._send(js)
312288
async function waitForEvent(env, event, breakerFunction, timeout = 5000, interval = 10) {
    const { type, urlPattern } = event;
    let intervalId, timeoutId;
    await new Promise((resolve, reject) => {
        const callback = {
            fn: ({ error }) => {
                clearTimeout(timeoutId);
                clearInterval(intervalId);
                if (error) {
                    reject(error);
                } else {
                    resolve();
                }
            },
            urlPattern,
        };

        timeoutId = setTimeout(() => {
            env.removeCallback(type, callback);
            clearInterval(intervalId);
            reject(new Error('Page navigation timeout'));
        }, timeout);

        intervalId = setInterval(() => {
            if (breakerFunction()) {
                clearTimeout(timeoutId);
                clearInterval(intervalId);
                env.removeCallback(type, callback);
                reject(new Error('Function was terminated by breaker'))
            }
        }, interval);

        env.addCallback(type, callback);
    });

    if (type === 'navigation') {
        await env._injectFiles(env._getVendors());
    }
}
327287
function whenReady(funcToExecute) {
    if (isReady()) {
        logger.info('Page is already loaded, instantly executing!');
        funcToExecute();
        return;
    }

    logger.info('Waiting for page to be ready');
    callbacksOnReady.push(funcToExecute);
}
51297
function ActionHandler(actionBlock, wait, dontCheckAlerts) {
    this.actionBlock = actionBlock;
    CommandHandler.call(this, "action", true);
    if (wait) {
        this.wait = true;
    }
    // note that dontCheckAlerts could be undefined!!!
    this.checkAlerts = (dontCheckAlerts) ? false : true;
}
1100852
function wait(ms = 0) {
  return function(val) {
    return new Promise(resolve => setTimeout(_ => resolve(val), ms));
  };
}
888332
async function handle(obj, scope, list, base) {
	for (let i = 0, l = list.length; i < l; i++) {
		if (next !== (await list[i].call(this, obj, scope, next))) {
			return;
		}
	}
	if (base) {
		return base.call(this, obj, scope, next);
	}
}
682045
async function () {
    const oThis = this
    ;

    try {
      const highestBlock = await this.getChainHighestBlock();

      // return if nothing more to do.
      if (highestBlock - 6 <= oThis.lastProcessedBlock) return oThis.schedule();

      // consider case in which last block was not processed completely

      oThis.fromBlock = oThis.snmData.lastProcessedBlock + 1;
      oThis.toBlock = highestBlock - 6;

      const events = await oThis.completeContract.getPastEvents(
        oThis.EVENT_NAME,
        {fromBlock: oThis.fromBlock, toBlock: oThis.toBlock},
        function (error, logs) {
          if (error) logger.error('getPastEvents error:', error);
          logger.log('getPastEvents done from block:', oThis.fromBlock, 'to block:', oThis.toBlock);
        }
      );
      await oThis.processEventsArray(events);

      oThis.schedule();
    } catch (err) {
      logger.info('Exception got:', err);

      if (oThis.interruptSignalObtained) {
        logger.info('Exiting Process....');
        process.exit(1);
      } else {
        oThis.reInit();
      }

    }
  }
38801
async function pause() {
  if (gT.cLParams.selActsDelay) {
    await gT.u.promise.delayed(gT.cLParams.selActsDelay);
  }
}
445797
function() {
    var pending = [],
        value, deferred;

    deferred = {

      resolve: function(val) {
        if (pending) {
          var callbacks = pending;
          pending = undefined;
          value = ref(val);

          if (callbacks.length) {
            nextTick(function() {
              var callback;
              for (var i = 0, ii = callbacks.length; i < ii; i++) {
                callback = callbacks[i];
                value.then(callback[0], callback[1]);
              }
            });
          }
        }
      },


      reject: function(reason) {
        deferred.resolve(reject(reason));
      },


      promise: {
        then: function(callback, errback) {
          var result = defer();

          var wrappedCallback = function(value) {
            try {
              result.resolve((callback || defaultCallback)(value));
            } catch(e) {
              exceptionHandler(e);
              result.reject(e);
            }
          };

          var wrappedErrback = function(reason) {
            try {
              result.resolve((errback || defaultErrback)(reason));
            } catch(e) {
              exceptionHandler(e);
              result.reject(e);
            }
          };

          if (pending) {
            pending.push([wrappedCallback, wrappedErrback]);
          } else {
            value.then(wrappedCallback, wrappedErrback);
          }

          return result.promise;
        }
      }
    };

    return deferred;
  }
500293
function async(value, bool) {
   var def = promise()
   setTimeout(function() {
 	   if(!bool) def.fulfill(value)
     else def.reject('error')
   }, 10)
   return def.promise
 }
199224
function () {
  let args = sliced(arguments)
  let done = args[args.length - 1]
  if (args.length < 2) {
    // not enought params
    return done()
  }

  let selector = args[0]
  if (typeof selector === 'string') {
    let callback = args[1]
    let timeout = null

    if (typeof callback === 'string') {
      let shouldBe = null

      if (typeof args[2] !== 'function') {
        shouldBe = args[2]
      }

      if (typeof args[3] === 'number') {
        timeout = args[3]
      }

      callback = (element) => _get(element, args[1]) === shouldBe
    } else if (typeof args[1] === 'number') {
      timeout = args[1]
    }

    if (args.length < 3) {
      callback = null
    }

    waitelem.apply({ timeout, callback }, [this, selector, done])
  } else {
    done()
  }
}
230255
function(func, context, args, async) {
    if (async) {
      _setTimeout(function() {
        func.apply(context, args);
      }, 0);
    } else {
      func.apply(context, args);
    }
  }
408952
function wait() {
  var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

  return new Promise(function (res) {
    return setTimeout(res, ms);
  });
}
762700
function callbackHandler(callback) {
        return function(error, data) {
            if (data === 'OK') {
                callback();
                return;
            }

            callback(error, deserializeResponse(data));
        };
    }
948478
def asynchronous(function, event):
    
    thread = Thread(target=synchronous, args=(function, event))
    thread.daemon = True
    thread.start()
303845
async function () {

        const log = []

        const a =       () => {                     log.push ('a')              }
        const b = async () => { await __.sleep (1); log.push ('b');             }
        const c =       () => {                     log.push ('c'); return 42   } // breaks here
        const d =       () => {                     log.push ('d');             } // will not be executed

        await __.each ([a, b, c], (fn, i, break_) =>
                                    __.then (fn, x => {
                                                    if (x === 42) break_ () }))

        $assert (log, ['a', 'b', 'c'])
    }