Handle `PG.connect()` callback results using Promise

@param resolve
@param reject
@param err
@param client
@param done
@returns {*}
4741
function catchResults (resolve, reject, err, client, done) {
	//debug.log('catchResults()...');
	if (err) {
		return reject(err);
	}
	resolve({"client":client, "done":done});
}
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);
		});
	}
73651
function(options, callback) {
    // Create a promise to defer to later
    var deferred = Bluebird.defer();

    // Fire the request
    request(this._buildRequestOptions(options), function(err, response, body) {
      // Handle Errors
      if (err) {
        // Usually a connection error (server unresponsive)
        err = new MuniError(err.message || 'Internal Server Error', err.code || 500);
      } else if (response.statusCode >= 400) {
        // Usually an intentional error from the server
        err = new MuniError(this._extractError(body), response.statusCode);
      }
      if (err) {
        debug.warn('Adapter Request Error with Code: %d', err.code);
        callback && callback(err);
        return deferred.reject(err);
      }

      // Handle Success
      debug.info('Adapter Request Sent with code: %d', response.statusCode);
      callback && callback(null, body);
      return deferred.resolve(body);
    }.bind(this));

    return deferred.promise;
  }
395676
function handleConnection(client) {
        // set ghostmode callbacks
        if (bs.options.get("ghostMode")) {
            addGhostMode(client);
        }

        client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients

        emitter.emit("client:connected", {
            ua: client.handshake.headers["user-agent"]
        });
    }
300844
function (message) {

            // forward the message to the local promise,
            // which will return a response promise
            var local = getLocal(message.to).promise;
            var response = local.dispatch(message.op, decode(message.args));
            var envelope;

            // connect the local response promise with the
            // remote response promise:

            // if the value is ever resolved, send the
            // fulfilled value across the wire
            response.then(function (resolution) {
                try {
                    resolution = encode(resolution);
                } catch (exception) {
                    try {
                        resolution = {"!": encode(exception)};
                    } catch (_exception) {
                        resolution = {"!": null};
                    }
                }
                envelope = JSON.stringify({
                    "type": "resolve",
                    "to": message.from,
                    "resolution": resolution
                });
                connection.put(envelope);
            }, function (reason) {
                try {
                    reason = encode(reason);
                } catch (exception) {
                    try {
                        reason = encode(exception);
                    } catch (_exception) {
                        reason = null;
                    }
                }
                envelope = JSON.stringify({
                    "type": "resolve",
                    "to": message.from,
                    "resolution": {"!": reason}
                });
                connection.put(envelope);
            }, function (progress) {
                try {
                    progress = encode(progress);
                    envelope = JSON.stringify({
                        "type": "notify",
                        "to": message.from,
                        "resolution": progress
                    });
                } catch (exception) {
                    try {
                        progress = {"!": encode(exception)};
                    } catch (_exception) {
                        progress = {"!": null};
                    }
                    envelope = JSON.stringify({
                        "type": "resolve",
                        "to": message.from,
                        "resolution": progress
                    });
                }
                connection.put(envelope);
            })
            .done();

        }
905515
function connect() {
      var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var callback = arguments[1];

      this.host = props.host || '127.0.0.1';
      this.port = props.port || 21000;
      this.resultType = props.resultType || null;
      this.timeout = props.timeout || 1000;
      this.transport = props.transport || _thrift2.default.TBufferedTransport;
      this.protocol = props.protocol || _thrift2.default.TBinaryProtocol;
      this.options = {
        transport: this.transport,
        protocol: this.protocol,
        timeout: this.timeout
      };

      var deferred = _thrift.Q.defer();

      var connection = _thrift2.default.createConnection(this.host, this.port, this.options);
      var client = _thrift2.default.createClient(_ImpalaService2.default, connection);

      connection.on('error', ImpalaClient.onErrorDeferred(deferred));

      connection.on('connect', function () {
        deferred.resolve('Connection is established.');
      });

      this.client = client;
      this.connection = connection;

      deferred.promise.nodeify(callback);
      return deferred.promise;
    }
646206
function ConnectedHandler(options) {
    var app = new Express(),
        webgmeUrl = options.webgmeUrl || 'http://127.0.0.1:' + gmeConfig.server.port,
        projects = {},
        certificate,
        timeoutId,
        webgmeToken,
        storage,
        server;

    options.port = options.port || (gmeConfig.server.port + 1);
    options.tokenRefreshInterval = options.tokenRefreshInterval || DEFAULT_TOKEN_REFRESH_INTERVAL;

    if (options.certificate) {
        // This is needed if the tls/ssl certificates are self signed.
        certificate = fs.readFileSync(options.certificate, 'utf-8');
        gmeConfig.socketIO.clientOptions.ca = certificate;
    }

    function getConnectedStorage(callback) {
        var deferred = Q.defer();

        if (storage) {
            deferred.resolve(storage);
        } else {
            logger.info('Establishing connection to webgme storage at', webgmeUrl);
            storage = Storage.createStorage(webgmeUrl, webgmeToken, logger, gmeConfig);
            storage.open(function (networkState) {
                if (networkState === CONSTANTS.STORAGE.CONNECTED) {
                    deferred.resolve(storage);
                } else {
                    // FIXME: We can handle more events that just CONNECTED
                    deferred.reject(new Error('Problems connecting to the webgme server, network state: ' +
                        networkState));
                }
            });
        }

        return deferred.promise.nodeify(callback);
    }

    /**
     *
     * @param {object} payload
     *
     * @example
     * payload =
     * {
     *    event: 'COMMIT',
     *    projectId: 'guest+MyProject',
     *    owner: 'guest',
     *    projectName: 'MyProject',
     *    hookId: 'MyWebHook',
     *    data: {
     *       projectId: "demo+Templates",
     *       commitHash: "#d8de3bdd38be13c43ea182058d397e9e28d4b4ef",
     *       userId: "demo"
     *       }
     *    }
     */
    function handleHook(payload) {
        var defer = Q.defer(),
            project,
            commitHash,
            core;

        if (payload.event !== CONSTANTS.WEBHOOK_EVENTS.COMMIT || payload.data.userId !== options.userId) {
            // We're only interested in events from our user..
            logger.info('Skipping event [', payload.event, '] triggered by [', payload.data.userId, ']');
            defer.resolve();
            return defer.promise;
        }

        commitHash = payload.data.commitHash;

        getConnectedStorage()
            .then(function () {
                if (projects.hasOwnProperty(payload.projectId)) {
                    return projects[payload.projectId];
                } else {
                    projects[payload.projectId] = Q.ninvoke(storage, 'openProject', payload.projectId)
                        .then(function (res) {
                            return res[0];
                        });

                    return projects[payload.projectId];
                }
            })
            .then(function (project_) {
                project = project_;

                return project.getCommits(commitHash, 1);
            })
            .then(function (commitObject) {
                core = new Core(project, {
                    globConf: gmeConfig,
                    logger: logger.fork('core')
                });

                return core.loadRoot(commitObject[0].root);
            })
            .then(function (rootNode) {
                logger.info('Name of root node is [', core.getAttribute(rootNode, 'name'), '] at [',
                    payload.projectName + commitHash.substring(0, 7) + ']');

                defer.resolve();
            })
            .catch(function (err) {
                logger.error(err);
                defer.reject(err);
            });

        return defer.promise;
    }

    function refreshToken() {
        var deferred = Q.defer(),
            req = superagent.get(webgmeUrl + '/api/user/token');

        logger.info('Will request new token at', webgmeUrl + '/api/user/token');

        if (!webgmeToken) {
            // Only use credentials for the first request (password may change)..
            req.set('Authorization', 'Basic ' +
                Buffer.from(options.userId + ':' + options.password).toString('base64'));
        } else {
            req.set('Authorization', 'Bearer ' + webgmeToken);
        }

        if (certificate) {
            req.ca(certificate);
        }

        req.end(function (err, res) {
            if (err) {
                deferred.reject(err);
                return;
            }

            if (typeof res.body.webgmeToken === 'string') {
                webgmeToken = res.body.webgmeToken;
                logger.info('Obtained new token from webgme server.');
                //logger.info(webgmeToken);

                if (storage) {
                    storage.setToken(webgmeToken);
                }

                deferred.resolve(res.body.webgmeToken);
            } else {
                deferred.reject(new Error(webgmeUrl + '/user/token did not provide webgmeToken.'));
            }

            timeoutId = setTimeout(refreshToken, options.tokenRefreshInterval);
        });

        return deferred.promise;
    }

    this.start = function (callback) {
        var deferred = Q.defer();

        app.use(bodyParser.json());

        app.post(['', '/'], function (req, res) {
            var payload = req.body;
            handleHook(payload)
                .finally(function () {
                });

            res.sendStatus(200);
        });

        refreshToken()
            .then(function () {
                server = app.listen(options.port);
                logger.info('Server listening at:  http://127.0.0.1:' + options.port);
            })
            .catch(deferred.reject);


        return deferred.promise.nodeify(callback);
    };

    this.stop = function (callback) {
        var deferred = Q.defer();

        clearTimeout(timeoutId);
        server.close();

        if (storage) {
            storage.close()
                .then(function () {
                    storage = null;
                    deferred.resolve();
                })
                .catch(deferred.reject);
        } else {
            deferred.resolve();
        }

        return deferred.promise.nodeify(callback);
    };
}
436933
private void handleConnection(Address address, Connection connection, Throwable error, CompletableFuture<Connection> future) {
    if (open) {
      if (error == null) {
        setupConnection(address, connection, future);
      } else {
        LOGGER.debug("{} - Failed to connect! Reason: {}", id, error);
        connect(future);
      }
    }
  }
1362705
function resolve(vResult0) {
			var fnThen;

			if (vResult0 === that) {
				reject(new TypeError("A promise cannot be resolved with itself."));
				return;
			}
			if (vResult0 instanceof SyncPromise) {
				if (vResult0.isFulfilled()) {
					resolve(vResult0.getResult());
					return;
				} else if (vResult0.isRejected()) {
					vResult0.caught(); // might have been uncaught so far
					reject(vResult0.getResult());
					return;
				} else {
					vResult0.caught(); // make sure it will never count as uncaught
					vResult0 = vResult0.getResult(); // unwrap to access native thenable
				}
			}

			iState = 0;
			vResult = vResult0;
			if (hasThen(vResult)) {
				try {
					fnThen = vResult.then;
				} catch (e) {
					// 2.3.3.2. If retrieving the property x.then results in a thrown exception e,
					// reject promise with e as the reason.
					reject(e);
					return;
				}
				if (typeof fnThen === "function") {
					call(fnThen.bind(vResult), resolve, reject);
					return;
				}
			}
			iState = 1;
			if (fnResolve) {
				fnResolve(vResult);
				fnReject = fnResolve = null; // be nice to the garbage collector
			}
		}
1206205
function(chain) {
      var method = status > 0 ? "resolve" :
                   status < 0 ? "reject" :
                   null;
      if (method) for (var i in chain) {
        chain[i][method](result);
      }
    }
106071
function doResolve(result) {
  let self = this;
  if (result === self) {
    // Promise Standard 2.3.1
    return doReject.call(
      self,
      new TypeError("Can not resolve 'Promise' itself")
    );
  }
  // Promise Standard 2.3.3.2
  try {
    // Promise Standard 2.3.2 and 2.3.3 can be merge
    // if result is a thenable(.then)
    let then = safelyToThen(result);
    if (then) {
      // Promise Standard 2.3.3.3
      safelyToExecutor(self, then.bind(result));
    } else {
      // [[ async ]]
      setTimeout(function() {
        // commonly case
        if (self.currentState === Shared.PENDING) {
          self.currentState = Shared.FULFILLED;
          self.valOrErr = result;
          for (let i = 0; i < self.onFulfilledCallback.length; i++) {
            self.onFulfilledCallback[i](result);
          }
          self.onFulfilledCallback = [];
        }
      }, 0);
    }
    // case: when then(doResolve, doReject) -> asyncToResolveOrReject -> func(arg) -> return self
    return self;
  } catch (error) {
    return doReject.call(self, error);
  }
}
449237
function resolvePromise(promise, state, value) {
        var onceWrapper = once();
        if (promise === value) {
            throw new TypeError('Promise resolved with itself');
        }
        if (promise[symbolState] === UNRESOLVED) {
            // should only get value.then once based on promise spec.
            var then = null;
            try {
                if (typeof value === 'object' || typeof value === 'function') {
                    then = value && value.then;
                }
            }
            catch (err) {
                onceWrapper(function () {
                    resolvePromise(promise, false, err);
                })();
                return promise;
            }
            // if (value instanceof ZoneAwarePromise) {
            if (state !== REJECTED && value instanceof ZoneAwarePromise &&
                value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
                value[symbolState] !== UNRESOLVED) {
                clearRejectedNoCatch(value);
                resolvePromise(promise, value[symbolState], value[symbolValue]);
            }
            else if (state !== REJECTED && typeof then === 'function') {
                try {
                    then.apply(value, [
                        onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false))
                    ]);
                }
                catch (err) {
                    onceWrapper(function () {
                        resolvePromise(promise, false, err);
                    })();
                }
            }
            else {
                promise[symbolState] = state;
                var queue = promise[symbolValue];
                promise[symbolValue] = value;
                // record task information in value when error occurs, so we can
                // do some additional work such as render longStackTrace
                if (state === REJECTED && value instanceof Error) {
                    value[__symbol__('currentTask')] = Zone.currentTask;
                }
                for (var i = 0; i < queue.length;) {
                    scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
                }
                if (queue.length == 0 && state == REJECTED) {
                    promise[symbolState] = REJECTED_NO_CATCH;
                    try {
                        throw new Error('Uncaught (in promise): ' + value +
                            (value && value.stack ? '\n' + value.stack : ''));
                    }
                    catch (err) {
                        var error_1 = err;
                        error_1.rejection = value;
                        error_1.promise = promise;
                        error_1.zone = Zone.current;
                        error_1.task = Zone.currentTask;
                        _uncaughtPromiseErrors.push(error_1);
                        api.scheduleMicroTask(); // to make sure that it is running
                    }
                }
            }
        }
        // Resolving an already resolved promise is a noop.
        return promise;
    }
19680
function rejected(reason) {
            var p = new Promise();
            p.then = then;
            states.reject(p, reason);
            return p;

            function then(_, onRejected) {
                try {
                    return resolve(typeof onRejected == 'function' ? onRejected(reason) : rejected(reason));
                } catch (e) {
                    return rejected(e);
                }
            }
        }
1239779
function promiseWrapper (resolve, reject) {
            // Wait for the process to exit
            process.on ("exit", (code) => {
                // Did the process crash?
                if (code !== 0) reject (process.stderr.textContent);

                // Resolve
                resolve (process.stdout.textContent);
            });

            // Pipe the script into stdin and end
            process.stdin.write (script);
            process.stdin.end ();
        }
855361
function _checkConnection(conn) {
  // Return Promise for getConnection callback wrapping
  return new Promise((resolve, reject) => {
    if (conn) {
      resolve(conn);
    } else {
      _pool.getConnection((err, conn) => {
        if (err) reject(err); // Reject this error
        else resolve(conn); // Resolve the connection
      })
    }
  });
}
906455
async function createSftpConnection(client) {
  return new Promise((resolve, reject) => {
    client.sftp((error, sftp) => (error ? reject(error) : resolve(sftp)));
  });
}
995452
function Promise(resolver) {
  if (!(this instanceof Promise)) {
    throw new TypeError('Constructor Promise requires `new`');
  }
  if (!isFunction(resolver)) {
    throw new TypeError('Must pass resolver function');
  }

  /**
   * @type {function(this:Promise,*=,function(*=),function(*=),Deferred):!Promise}
   * @private
   */
  this._state = PendingPromise;

  /**
   * @type {*}
   * @private
   */
  this._value = [];

  /**
   * @type {boolean}
   * @private
   */
  this._isChainEnd = true;

  doResolve(
    this,
    adopter(this, FulfilledPromise),
    adopter(this, RejectedPromise),
    { then: resolver }
  );
}