usage:  promiseChain(cb) <-- this is the callback for eventual success or error ( fn, [arg, arg, arg], function (a,b,c) { success(a,b,c) }) ( fn2, [args] ) () <-- this kicks it off.  promiseChain.call(someObj, cb) <-- bind this-context for all functions
514009
function promiseChain (cb) {
  var steps = []
    , vals = []
    , context = this
  function go () {
    var step = steps.shift()
    if (!step) return cb()
    try { step[0].apply(context, step[1]) }
    catch (ex) { cb(ex) }
  }
  return function pc (fn, args, success) {
    if (arguments.length === 0) return go()
    // add the step
    steps.push
      ( [ fn
        , (args || []).concat([ function (er) {
            if (er) return cb(er)
            var a = Array.prototype.slice.call(arguments, 1)
            try { success && success.apply(context, a) }
            catch (ex) { return cb(ex) }
            go()
          }])
        ]
      )
    return pc
  }
}
792004
function nodeify(promise, callback) {
  if (!callback) return promise;
  if (typeof callback !== 'function') {
    throw new TypeError('Expected callback to be a function');
  }
  wrapForCallback(promise, callback);
}
53457
function callbackOnce(err, arg) {
            var cb = callback;
            callback = null;
            if (cb) { cb(err, arg); }
        }
541218
function chainAndCall(chainer) {
    return function(/*step1, step2, ...*/) {
        var steps = slice.call(arguments);
	    var callback = steps.pop();
	    chainer.apply(null, steps)(callback);
    };
}
888699
function notifyIsolated(self,cb,chain) {
		var ret, _then;
		try {
			if (cb === false) {
				chain.reject(self.msg);
			}
			else {
				if (cb === true) {
					ret = self.msg;
				}
				else {
					ret = cb.call(void 0,self.msg);
				}

				if (ret === chain.promise) {
					chain.reject(TypeError("Promise-chain cycle"));
				}
				else if (_then = isThenable(ret)) {
					_then.call(ret,chain.resolve,chain.reject);
				}
				else {
					chain.resolve(ret);
				}
			}
		}
		catch (err) {
			chain.reject(err);
		}
	}
430906
function (cb) {
            if (cb) {
                if (isPromise(cb)) {
                    cb = cb.errback;
                }
                if (this.__fired && this.__error) {
                    this.__callNextTick(cb, this.__error);
                } else {
                    this.__errorCbs.push(cb);
                }
            }
            return this;
        }
379441
function chainQueryRun (safeCon, arg, currentObj) {
  
  objAdder(safeCon, currentObj);
  
  var stream;
  try {
    stream = safeCon.query.apply(safeCon, arg);
  } catch(e) {
    return currentObj.rollback(e);
  }
  
  autoErrorRollback(currentObj);
  onewayEventConnect(stream, currentObj);
  
  if (currentObj._autoCommit) {
    autoCommitReady(safeCon, currentObj);
  }
  
  stream.on('error', function(e){
    safeCon._errorState = true;
  });
  
  currentObj.on('end', function(){
    safeCon._count -= 1;
  });
  
  safeCon._count += 1;
  currentObj.stream = stream;
  currentObj.emit('nextChain', safeCon);
}
685422
function tryFn(fn, args) {
  try {
    return Promise.resolve(fn.apply(null, args));
  } catch (e) {
    return Promise.reject(e);
  }
}
676609
function promiseTry(callback) {
  try {
    const maybePromise = callback();

    if (isPromise(maybePromise)) {
      return maybePromise;
    } else {
      return Promise.resolve(maybePromise);
    }
  } catch (err) {
    return Promise.reject(err);
  }
}
656879
function (promise, i) {
            var self = this;
            promise.then(
                function () {
                    var args = argsToArray(arguments);
                    args.unshift(i);
                    spreadArgs(self.callback, args, self);
                    promise = i = self = null;
                },
                function () {
                    var args = argsToArray(arguments);
                    args.unshift(i);
                    spreadArgs(self.errback, args, self);
                    promise = i = self = null;
                });
        }
143544
function query(){
		//console.log(arguments[0]);
		var self = this;
		var args = arguments;
		var last_arg = args[args.length - 1];
		var bHasCallback = (typeof last_arg === 'function');
		if (!bHasCallback) // no callback
			last_arg = function(){};

		var count_arguments_without_callback = bHasCallback ? (args.length-1) : args.length;
		var new_args = [];

		for (var i=0; i<count_arguments_without_callback; i++) // except callback
			new_args.push(args[i]);
		if (!bHasCallback && !bCordova)
			return new Promise(function(resolve){
				new_args.push(resolve);
				self.query.apply(self, new_args);
			});
		takeConnectionFromPool(function(connection){
			// add callback that releases the connection before calling the supplied callback
			new_args.push(function(rows){
				connection.release();
				last_arg(rows);
			});
			connection.query.apply(connection, new_args);
		});
	}
1023838
function createChainedFunction(one, two) {
    return function chainedFunction() {
      one.apply(this, arguments);
      two.apply(this, arguments);
    };
  }
1080787
function(cb, next, method) {
        return function(value) {
            if (typeof cb !== 'function')                            /*  [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4]  */
                next[method].call(next, value);                      /*  [Promises/A+ 2.2.7.3, 2.2.7.4]  */
            else {
                var result;
                try {
                    if (value instanceof Promise) {
                        result = value.then(cb);
                    }
                    else result = cb(value);
                }                          /*  [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2]  */
                catch (e) {
                    next.reject(e);                                  /*  [Promises/A+ 2.2.7.2]  */
                    return;
                }
                resolve(next, result);                               /*  [Promises/A+ 2.2.7.1]  */
            }
        };
    }
77630
function wrapFn(fn) {

  var argCount = fn.length;

  if (argCount < 2) {
    // promise style worker
    return async function(context) {
      return await fn(context);
    };
  }

  if (argCount === 2) {
    // callback style worker
    return function(context) {

      return new Promise(function(resolve, reject) {
        try {
          fn(context, function(err, data) {
            if (err) {
              reject(err);
            } else {
              resolve(data);
            }
          });
        } catch (err) {
          reject(err);
        }
      });

    };
  }

  throw new Error('expected Promise or callback style fn');
}
734924
function listenAndPromise(callback, bindContext) {
        var me = this;
        bindContext = bindContext || this;
        this.willCallPromise = (this.willCallPromise || 0) + 1;

        var removeListen = this.listen(function() {

            if (!callback) {
                throw new Error("Expected a function returning a promise but got " + callback);
            }

            var args = arguments,
                returnedPromise = callback.apply(bindContext, args);
            return me.promise.call(me, returnedPromise);
        }, bindContext);

        return function () {
          me.willCallPromise--;
          removeListen.call(me);
        };

    }
407893
public <R> Promise<T> chain(final Function<T, Promise<R>> res) {
        final Promise<T> self = this;
        return new Promise<>(resolver -> {
            self.then(t -> {
                Promise<R> chained = res.apply(t);
                chained.then(t2 -> resolver.result(t));
                chained.failure(e -> resolver.error(e));
            });
            self.failure(e -> resolver.error(e));
        });
    }
555159
function Promise(callback, handler) {
			// The `handler` variable points to the function that will
			// 1) handle a .then(resolved, rejected) call
			// 2) handle a resolve or reject call (if the first argument === `is`)
			// Before 2), `handler` holds a queue of callbacks.
			// After 2), `handler` is a finalized .then handler.
			handler = function pendingHandler(resolved, rejected, value, queue, then, i) {
				queue = pendingHandler.q;

				// Case 1) handle a .then(resolved, rejected) call
				if (resolved != is) {
					return Promise(function (resolve, reject) {
						queue.push({ p: this, r: resolve, j: reject, 1: resolved, 0: rejected });
					});
				}

				// Case 2) handle a resolve or reject call
				// (`resolved` === `is` acts as a sentinel)
				// The actual function signature is
				// .re[ject|solve](<is>, success, value)

				// Check if the value is a promise and try to obtain its `then` method
				if (value && (is(func, value) | is(obj, value))) {
					try { then = value.then; }
					catch (reason) { rejected = 0; value = reason; }
				}
				// If the value is a promise, take over its state
				if (is(func, then)) {
					function valueHandler(resolved) {
						return function (value) { then && (then = 0, pendingHandler(is, resolved, value)); };
					}
					try { then.call(value, valueHandler(1), rejected = valueHandler(0)); }
					catch (reason) { rejected(reason); }
				}
				// The value is not a promise; handle resolve/reject
				else {
					// Replace this handler with a finalized resolved/rejected handler
					handler = function (Resolved, Rejected) {
						// If the Resolved or Rejected parameter is not a function,
						// return the original promise (now stored in the `callback` variable)
						if (!is(func, (Resolved = rejected ? Resolved : Rejected)))
							return callback;
						// Otherwise, return a finalized promise, transforming the value with the function
						return Promise(function (resolve, reject) { finalize(this, resolve, reject, value, Resolved); });
					};
					// Resolve/reject pending callbacks
					i = 0;
					while (i < queue.length) {
						then = queue[i++];
						// If no callback, just resolve/reject the promise
						if (!is(func, resolved = then[rejected]))
							(rejected ? then.r : then.j)(value);
						// Otherwise, resolve/reject the promise with the result of the callback
						else
							finalize(then.p, then.r, then.j, value, resolved);
					}
				}
			};
			// The queue of pending callbacks; garbage-collected when handler is resolved/rejected
			handler.q = [];

			// Create and return the promise (reusing the callback variable)
			callback.call(callback = { then:    function (resolved, rejected) { return handler(resolved, rejected); },
					"catch": function (rejected)           { return handler(0,        rejected); } },
				function (value)  { handler(is, 1,  value); },
				function (reason) { handler(is, 0, reason); });
			return callback;
		}