Return a promise with results

@method handlePromise
@param {Object} query - mongoose query object
@param {Object} q - query
@param {Object} model - mongoose model
@param {Number} resultsPerPage
@returns {Promise}
323901
function handlePromise(query, q, model, resultsPerPage) {
  return Promise.all([
    query.exec(),
    model.count(q).exec()
  ]).spread(function(results, count) {
    return [
      results,
      Math.ceil(count / resultsPerPage) || 1,
      count
    ]
  });
}
1312486
function promise(p) {
        var me = this;

        var canHandlePromise =
            this.children.indexOf("completed") >= 0 &&
            this.children.indexOf("failed") >= 0;

        if (!canHandlePromise){
            throw new Error("Publisher must have \"completed\" and \"failed\" child publishers");
        }

        p.then(function(response) {
            return me.completed(response);
        }, function(error) {
            return me.failed(error);
        });
    }
828025
function query(q) {
  var filter = Object.keys(q);
  var isValid;
  var valid;
  var val;

  return this.reduce((list, ps) => {
    isValid = filter.every(key => {
      val = q[key];
      valid = true;

      if (typeof val === 'string') {
        if (val.indexOf('<') > -1) {
          valid = ps[key] < cleanValue(val, '<');
        }

        if (valid && val.indexOf('>') > -1) {
          valid = ps[key] > cleanValue(val, '>');
        }

        if (valid && val.indexOf('~') > -1) {
          valid = ps[key].indexOf(q[key].replace('~', '')) > -1;
        }
      } else {
        valid = ps[key] === val;
      }

      return valid;
    });

    if (isValid) list.push(ps);

    return list;
  }, []);
}
1019169
function executeRelated () {
    // skip unless related records are specified by with or resolve
    if (!defined(this.args.with) && !this.args.resolve) {
        return
    }
    // skip if select is only for ids
    if (this.select.isSelectOnlyIds) {
        return
    }
    // add related queries to promise chain
    this.promise = this.promise.then(results => {
        // skip if there are no results
        if (!results.length) {
            return results
        }
        // iterate over results loading related records
        return Promise.map(results, result => this.executeRelatedResult(result), {
            concurrency: this.model.concurrency,
        })
    })
}
484967
function paginate(reqOptions, link, memo) {
	const links = link.split(/,\s*/);
	let matches;
	links.some(function(link) {
		matches = link.trim().match(/<(.+)>;\s*rel="next"/);
		return matches !== null;
	});
	// End of pagination
	if(!matches) {
		return Promise.resolve(memo);
	}
	return new Promise(function(resolve, reject) {
		reqOptions.url = matches[1];
		request(reqOptions, function(err, res, body) {
			paginate(reqOptions, res.headers.link, memo.concat(JSON.parse(body))).then(resolve);
		});
	});
}
344164
function (req, res) {
    BackboneModel
      .find(_.extend({ limit: 999 }, req.query))
      .then(function (models) {
        res.json(_.pluck(models, 'json'));
      })
      .catch(function (error) {
        sails.log.error(error);
        res.status(500).json(error);
      });
  }
486671
function(query) {
        var self = this;
        return Q.ninvoke(fs, 'readdir', path.join(this.backend.options.path, this.name))
            .then(function(files) {
                return Q.all(files.map(function(f) {
                    return self.get(f);
                }));
            })
            .then(function(vals) {
                return _.query(vals, query);
            });
    }
312741
function syncPromise(promise) {
  let isDone = false;
  let res, err;

  promise.then(
    value => {
      res = value;
      isDone = true;
    },
    error => {
      err = error;
      isDone = true;
    }
  );

  deasync.loopWhile(() => !isDone);

  if (err) {
    throw err;
  }

  return res;
}
564522
function reversePromises (promises) {
    return promises.map(function (promise) {
      var d = $q.defer();
      promise.then(d.reject, d.resolve);
      return d.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;
        }
672014
function fetch (fetchNum, offset) {
    // if all records already fetched resolve with undefined
    if (this.done) {
        return Promise.resolve([])
    }
    // set default fetchNum
    if (!fetchNum) {
        fetchNum = this.fetchNum
    }
    // if offset is set then set fetched with offset
    if (offset) {
        this.fetched = offset
    }
    // if fetchNum exceeds numner of remaining records then set to max
    fetchNum = _.clamp(fetchNum, this.length - this.fetched)
    // get list of ids to fetch
    var ids = this.ids.slice(this.fetched, this.fetched + fetchNum)
    // create where args for records query
    var whereArgs = {id: ids}
    // if isDeleted was set on original query then set for fetch
    if (defined(this.query.args.where.isDeleted)) {
        whereArgs.isDeleted = this.query.args.where.isDeleted
    }
    // fetch records
    return this.query.model.query({
        all: true,
        allow: this.query.args.allow,
        cache: this.query.args.cache,
        plain: this.query.args.plain,
        raw: this.query.args.raw,
        resolve: this.query.args.resolve,
        session: this.query.session,
        where: whereArgs,
        with: this.query.args.with,
        view: this.applyView ? this.query.args.view : false,
    })
    .then(records => {
        // add number of fetched records to count of fetched
        this.fetched += fetchNum
        // set done to true when all records fetched
        if (this.fetched === this.length) {
            this.done = true
        }

        return records
    })
}
431434
function formAsPromise (req, modelName, formDsl) {

    return new Promise((resolve, reject) => {

        form(req, modelName, (err, decoratedForm) => {

            if (err) {
                return reject(err);
            }

            return resolve(decoratedForm);

        }, formDsl);

    });

}
1326555
function query(connection, ...params){
    return new Promise(function(resolve, reject){
        // execute query
        connection.query(...params, function(err, result, fields){
            if (err){
                reject(err);
            }else{
                resolve([result, fields]);
            }
        });
    });
}
277688
function runQuery(query, connection) {
  const incomplete = false;

  return new Promise((resolve, reject) => {
    const client = hdb.createClient({
      host: connection.host,
      port: connection.hanaport,
      database: connection.hanadatabase,
      user: connection.username,
      password: connection.password,
      schema: connection.hanaSchema
    });

    client.on('error', err => {
      console.error('Network connection error', err);
      return reject(err);
    });

    client.connect(err => {
      if (err) {
        console.error('Connect error', err);
        return reject(err);
      }
      return client.execute(query, function(err, rs) {
        let rows = [];

        if (err) {
          client.disconnect();
          return reject(err);
        }

        if (!rs) {
          client.disconnect();
          return resolve({ rows, incomplete });
        }

        if (!rs.createObjectStream) {
          // Could be row count or something
          client.disconnect();
          return resolve({ rows: [{ result: rs }], incomplete });
        }

        const stream = rs.createObjectStream();

        stream.on('data', data => {
          if (rows.length < connection.maxRows) {
            return rows.push(data);
          }
          client.disconnect();
          return resolve({ rows, incomplete: true });
        });

        stream.on('error', error => {
          client.disconnect();
          return reject(error);
        });

        stream.on('finish', () => {
          client.disconnect();
          return resolve({ rows, incomplete });
        });
      });
    });
  });
}
665959
function(query) {
    var qparts = getQueryParts(goog.string.trim(query));

    // if it's trivial, avoid iteration and zipping costs
    if (qparts.length == 1) {
      // We optimize this case here to prevent dispatch further down the
      // chain, potentially slowing things down. We could more elegantly
      // handle this in filterDown(), but it's slower for simple things
      // that need to be fast (e.g., '#someId').
      var tef = getElementsFunc(qparts[0]);
      return function(root) {
        var r = tef(root, []);
        if (r) { r.nozip = true; }
        return r;
      }
    }

    // otherwise, break it up and return a runner that iterates over the parts
    // recursively
    return function(root) {
      return filterDown(root, qparts);
    }
  }
1207290
function process_endpoint_result(raw_result) {
                const store_result = op.execute_on_store(raw_result);
                const result = NOOP === store_result
                    ? raw_result
                    : store_result
                    ;
                return resolve_promise(prepare_result(result));
            }
311084
function(req, res, next) {
      console.log('executing graphql query');
      if (req.url === '/graphql') {
        var schema = getGraphQLSchemaFrom(sails.models);
        require('express-graphql')({
            schema: schema,
            pretty: true
          })(req, res);
      } else {
        return next();
      }
    }