this returns a promise and the resolve-function
which can be called to resolve before the timeout has passed
@param  {Number}  [ms=0] [description]
432538
function waitResolveable() {
    var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

    var ret = {};
    ret.promise = new Promise(function (res) {
        ret.resolve = function (x) {
            return res(x);
        };
        setTimeout(res, ms);
    });
    return ret;
}
1215410
function resolveItem(arg) {
  if (Array.isArray(arg)) {
    return resolveArray(arg);
  } else if (Object.prototype.toString.call(arg) === '[object Function]') {
    //is a function
    return Promise.method(arg)().then(resolveItem);
  } else if (isThenable(arg)) {
    //is a promise
    return arg.then(resolveItem);
  } else if (arg && typeof arg === 'object') {
    //is an object
    if (typeof arg.toString === 'function') {
      var value = arg.toString();
      if (value !== '[object Object]') {
        //with a valid toString
        return Promise.resolve(value);
      }
    }
    return resolveObject(arg);
  } else {
    //Yeah! a value
    return Promise.resolve(arg);
  }
}
82239
function (fn, repeatTest = 0, args = []) {
    let result, error

    /**
     * if a new hook gets executed we can assume that all commands should have finised
     * with exception of timeouts where `commandIsRunning` will never be reset but here
     */
    // commandIsRunning = false

    try {
        result = fn.apply(this, args)
    } catch (e) {
        error = e
    }

    /**
     * handle errors that get thrown directly and are not cause by
     * rejected promises
     */
    if (error) {
        if (repeatTest) {
            return executeAsync(fn, --repeatTest, args)
        }
        return new Promise((resolve, reject) => reject(error))
    }

    /**
     * if we don't retry just return result
     */
    if (repeatTest === 0 || !result || typeof result.catch !== 'function') {
        return new Promise(resolve => resolve(result))
    }

    /**
     * handle promise response
     */
    return result.catch((e) => {
        if (repeatTest) {
            return executeAsync(fn, --repeatTest, args)
        }

        e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n')
        return Promise.reject(e)
    })
}
1128877
function promiseWrap(x) {
  if(x.then && typeof x.then === "function") {
    return x;    
  }
  var deferred = q.defer();
  deferred.resolve(x);
  return deferred.promise;
}
1085806
function Q(resolver) {
          if (!angular.isFunction(resolver)) {
            throw new Error('missing resolver function');
          }

          var deferred = $q.defer();

          function resolveFn(value) {
            deferred.resolve(value);
          }

          function rejectFn(reason) {
            deferred.reject(reason);
          }

          resolver(resolveFn, rejectFn);

          return deferred.promise;
        }
203478
function buildAsyncSaveFun(_this, _oldSave, _promise, _oldPromise) {
    return function() {

      // swap promises so save behaves like it has been called during the original call.
      var currentPromise = _this.$promise;
      _this.$promise = _oldPromise;

      // when save resolves, the timeout promise is resolved and the last resource promise returned
      // so it behaves
      _oldSave.call(_this).$promise.then(
        function(_data) {
          _promise.resolve(_data);
          _this.$promise = currentPromise;
        }, function(_reason) {
          _promise.reject(_reason);
          _this.$promise = currentPromise;
        }
      );

      _this.$dmStatus = null;
    };
  }
1257942
def _wait_for_completion(conn, promise, wait_timeout, msg):
    '''
    
    '''
    if not promise:
        return
    wait_timeout = time.time() + wait_timeout
    while wait_timeout > time.time():
        time.sleep(5)
        operation_result = conn.get_request(
            request_id=promise['requestId'],
            status=True)

        if operation_result['metadata']['status'] == "DONE":
            return
        elif operation_result['metadata']['status'] == "FAILED":
            raise Exception(
                "Request: {0}, requestId: {1} failed to complete:\n{2}".format(
                    msg, six.text_type(promise['requestId']),
                    operation_result['metadata']['message']
                )
            )

    raise Exception(
        'Timed out waiting for asynchronous operation {0} "{1}" to complete.'.format(
            msg, six.text_type(promise['requestId'])
        )
    )
1353679
function PromiseFactory() {
	var deferred = whenjs.defer();
	//var timeout = setTimeout(function () { console.log(t, 'Promise timed out')}, 3000);

	this.reject = function (err) {
		deferred.reject(err);
	};
	this.resolve = function (val) {
	//	clearTimeout(timeout);
		deferred.resolve(val);
	};
	this.promise = function () {
		return deferred.promise;
	};
}
990583
function defer() /*: { promise: Promise, resolve: resolveHandler, reject: rejectHandler }*/ {
    let resolve, reject;
    const promise = new Promise((...args) => [ resolve, reject ] = args);
    return { promise, resolve, reject };
}
941605
function makePromise(requestInstance, promiseFactoryFn) {

  // Resolver function wich assigns the promise (resolve, reject) functions
  // to the requestInstance
  function Resolver(resolve, reject) {
    this._resolve = resolve;
    this._reject = reject;
  }

  return promiseFactoryFn(Resolver.bind(requestInstance));
}
1339724
function (url, data, timeout) {

   log.debug("new http_post request", url, data, timeout);

   var d = when.defer();
   var req = new XMLHttpRequest();
   req.withCredentials = true; // pass along cookies
   req.onreadystatechange = function () {

      if (req.readyState === 4) {

         // Normalize IE's response to HTTP 204 when Win error 1223.
         // http://stackoverflow.com/a/10047236/884770
         //
         var status = (req.status === 1223) ? 204 : req.status;

         if (status === 200) {

            // response with content
            //
            d.resolve(req.responseText);

         } if (status === 204) {

            // empty response
            //
            d.resolve();

         } else {

            // anything else is a fail
            //
            var statusText = null;
            try {
               statusText = req.statusText;
            } catch (e) {
               // IE8 fucks up on this
            }
            d.reject({code: status, text: statusText});
         }
      }
   }

   req.open("POST", url, true);
   req.setRequestHeader("Content-type", "application/json; charset=utf-8");

   if (timeout > 0) {
      req.timeout = timeout; // request timeout in ms

      req.ontimeout = function () {
         d.reject({code: 501, text: "request timeout"});
      }
   }

   if (data) {
      req.send(data);
   } else {
      req.send();
   }

   if (d.promise.then) {
      // whenjs has the actual user promise in an attribute
      return d.promise;
   } else {
      return d;
   }
}
321802
function resolver(obj) {
  return new Promise(function(resolve, reject) {
    _.isEmpty(obj.results) ? reject(new Error(JSON.stringify(obj.errors))) : resolve(obj.results);
  })
}
869062
function(delay) {
        var timer,
            promise = this.then(function(val) {
                var defer = new Deferred();
                timer = setTimeout(
                    function() {
                        defer.resolve(val);
                    },
                    delay);

                return defer.promise();
            });

        promise.always(function() {
            clearTimeout(timer);
        });

        return promise;
    }
403117
function resolveWhen() {
          var dfd = pendings[handle];
          if (dfd) {
            dfd.forEach(function (promise) {
              promise.resolve(instance);
            });
            delete pendings[handle];
          }
        }
1321846
function () {
    const oThis = this
      , promiseArray = [];

    return new Promise(async function (onResolve, onReject) {
      for (var chain in setupConfig.chains) {
        promiseArray.push(oThis._isRunning(chain));
      }
      return Promise.all(promiseArray).then(onResolve);
    });
  }
968541
function(func, resolves = false){
    if(typeof resolves !== 'boolean' && typeof resolves !== 'number' && resolves != 'all'){
      throw new Error('Invalid value submitted for \'resolves\' argument.')
    }
    return function(){
      return new Promise((resolve, reject)=>{
        var params = [...arguments, function(...args){

          //check for error hooks
          var error = false;
          for(let arg of args){
            if(arg instanceof Error){
              error = arg;
              break;
            }
          }

          if(error){
            reject(error)
          }else{
            switch(resolves){
              case false:
                resolve(arguments.length == 1 ? arguments[0] : arguments[1])
                break;
              case true:
                resolve(true)
                break;
              case 'all':
                resolve(args)
                break;
              default:
                resolve(args[resolve])
            }
          }
        }]
        func.apply(null, params)
      })
    }
  }
1293763
@Contract(pure = true)
	@NotNull
	public static <T> Promise<T> timeout(@NotNull Promise<T> promise, long delay) {
		if (promise.isComplete()) return promise;
		if (delay <= 0) return Promise.ofException(TIMEOUT_EXCEPTION);
		return promise.next(new NextPromise<T, T>() {
			@Nullable ScheduledRunnable schedule = getCurrentEventloop()
					.delay(delay,
							() -> {
								schedule = null;
								tryCompleteExceptionally(TIMEOUT_EXCEPTION);
							});

			@Override
			public void accept(T result, @Nullable Throwable e) {
				if (schedule != null) {
					schedule.cancel();
					schedule = null;
				}
				if (e == null) {
					tryComplete(result);
				} else {
					tryCompleteExceptionally(e);
				}
			}
		});
	}