How to use the co.wrap function in co

To help you get started, we’ve selected a few co examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github twosigma / git-meta / test / util / include.js View on Github external
describe("includeExistingRepo", function () {
        after(TestUtil.cleanup);

        // for these tests, "externalRepo" represents the repository to be 
        // included and "submoduleRepo" represents the submodule once it 
        // has been included inside "repo"  

        let repo, externalRepo, path;
        before(co.wrap(function *() {
            repo = yield TestUtil.createSimpleRepository();
            externalRepo = yield TestUtil.createSimpleRepository();
            path = "foo";
            yield Include.include(repo, externalRepo.workdir(), path);
        }));

        it("should include in the correct path", co.wrap(function *() {
            const pathExists = 
                yield TestUtil.pathExists(repo.workdir() + path);
            assert(pathExists, "path should exist");

            const submoduleRepo = 
                yield NodeGit.Repository.open(repo.workdir() + path);
            assert(submoduleRepo.workdir(), "repository should be created");
        }));
github tencentyun / wafer-node-server-sdk / lib / tunnel / tunnel-api.js View on Github external
'content': messageContent,
        });

        return this.emitPacket(tunnelIds, packetType, packetContent);
    },

    emitPacket(tunnelIds, packetType, packetContent) {
        let param = { tunnelIds, 'type': packetType };
        if (packetContent) {
            param.content = packetContent;
        }

        return this._sendRequest('/ws/push', [param], false);
    },

    _sendRequest: co.wrap(function *(apiPath, apiParam, withTcKey) {
        let url = config.getTunnelServerUrl() + apiPath;
        let data = this._packReqData(apiParam, withTcKey);

        let params = { url, 'body': data };

        let begin = Date.now();
        let result = yield net.jsonPost(params);
        let end = Date.now();

        let statusCode = result[0].statusCode;
        let body = result[1];

        // 记录请求日志
        debug(`POST ${url} => [${statusCode}]`, {
            '[请求]': data,
            '[响应]': body,
github twosigma / git-meta / node / lib / util / list_files.js View on Github external
/**
 * Return a list the files in the specified `repo` and its *open* submodules,
 * relative to the root of the repository, or to the optionally specified
 * `relativePath` if provided.  Note that the order of the list is
 * not defined.  Note that if `relativePath` is provided, no files will be
 * listed that are not within that subdirectory.  The behavior is undefined
 * unless `relativePath` (if provided) is a valid relative path and has no
 * trailing slash.
 *
 * @async
 * @param {NodeGit.Repository} repo
 * @param {String}             [relativePath]
 * @return [String]
 */
exports.listFiles = co.wrap(function *(repo, relativePath) {
    assert.instanceOf(repo, NodeGit.Repository);
    if (undefined !== relativePath && null !== relativePath) {
        assert.isString(relativePath);
        assert.notEqual(relativePath, "");
        assert.notEqual(relativePath[relativePath.length - 1], "/");
        assert(!path.isAbsolute(relativePath));
    }
    const subNames = new Set(yield SubmoduleUtil.getSubmoduleNames(repo));
    const openSubs = yield SubmoduleUtil.listOpenSubmodules(repo);

    const result = [];

    let withSlash;  // the relative path with a suffixed '/'
    if (relativePath) {
        withSlash = relativePath + "/";
    }
github fontello / fontello / lib / system / init / server.js View on Github external
WorkerQueue.prototype.fork = function () {
  cluster.setupMaster({ args: [ 'worker-queue' ] });

  let worker = cluster.fork(),
      log = this.__pool.log;

  worker.on('online', co.wrap(function* () {
    try {
      // Set scheduling policy to SCHED_IDLE (`-i` flag);
      // `0` is only possible value for priority ('cause this policy doesn't allow to set it)
      yield execFile('chrt', [ '-i', '-p', '0', worker.process.pid ]);
    } catch (__) {
      // If `chrt` not exists, try fallback to `renice`.
      try {
        yield execFile('renice', [ '-n', '19', '-p', worker.process.pid ]);
        log.warn('Cannot set scheduling policy for queue using `chrt`, falling back to `renice`');
      } catch (___) {
        log.error('Cannot lower priority for queue ' +
          '(both `renice` and `chrt` have failed), continuing with default priority');
      }
    }
  }));
github twosigma / git-meta / node / lib / util / destitch_util.js View on Github external
const pushOne = co.wrap(function *(push) {
        const sha = push.sha;
        const refName = SyntheticBranchUtil.getSyntheticBranchForCommit(sha);
        yield GitUtil.push(repo, push.url, sha, refName, true, true);
    });
    yield DoWorkQueue.doInParallel(toPush, pushOne);
});

/**
 * Record the specified `newCommits` to local reference notes in the specified
 * `repo`.
 *
 * @param {NodeGit.Repository} repo
 * @param {Object}             newCommits  sha to { metaRepoCommit, subCommits}
 */
exports.recordLocalNotes = co.wrap(function *(repo, newCommits) {
    assert.instanceOf(repo, NodeGit.Repository);
    assert.isObject(newCommits);
    const content = {};
    Object.keys(newCommits).forEach(sha => {
        content[sha] = JSON.stringify(newCommits[sha], null, 4);
    });
    yield BulkNotesUtil.writeNotes(repo,
                                   exports.localReferenceNoteRef,
                                   content);
});

/**
 * Create a destitched version of the specified `commitish`, including any
 * ancestors for which destitched versions cannot be found, in the specified
 * `repo`.  Use the specified `metaRemote` to fetch neede meta-repo commits and
 * to resolve submodule URLs.  Use the notes stored in
github tjmehta / coworkers / lib / application.js View on Github external
messageHandler (queueName) {
    const self = this
    const middlewares = this.middlewares.concat(this.queueMiddlewares[queueName])
    const mwPromise = co.wrap(koaCompose(middlewares))

    /**
     * message handler for the queue w/ queueName
     * @param  {object} message  rabbitmq message
     * @param  {Context} [_MockContext] optional, can be used for testing
     * @return {Promise} middleware chain promise
     */
    return function (message, _MockContext) {
      const context = _MockContext
        ? new _MockContext(self, queueName, message)
        : new Context(self, queueName, message)

      return mwPromise.call(context).then(function () {
        respond.call(context)
      }).catch(function (err) {
        Context.onerror(context, err)
github heroku / heroku-apps / commands / config / set.js View on Github external
description: 'set one or more config vars',
  help: `Examples:

 $ heroku config:set RAILS_ENV=staging
 Setting config vars and restarting example... done
 RAILS_ENV: staging

 $ heroku config:set RAILS_ENV=staging RACK_ENV=staging
 Setting config vars and restarting example... done
 RAILS_ENV: staging
 RACK_ENV:  staging
 `,
  needsApp: true,
  needsAuth: true,
  variableArgs: true,
  run: cli.command(co.wrap(run))
};

module.exports.set = cmd;
module.exports.add = extend({}, cmd);
module.exports.add.command = 'add';
github egoist / poi / lib / detect-free-port.js View on Github external
'use strict'
const co = require('co')
const detect = require('detect-port')
const chalk = require('chalk')
const terminalUtils = require('./terminal-utils')

module.exports = co.wrap(function * (DEFAULT_PORT) {
  const port = yield detect(DEFAULT_PORT)

  if (port === DEFAULT_PORT) {
    return port
  }

  terminalUtils.clearConsole()

  const question =
    chalk.yellow(`Something is already running on port ${DEFAULT_PORT}.`) +
    '\n\nWould you like to run the app on another port instead?'

  const shouldChangePort = yield terminalUtils.prompt(question, true)

  return shouldChangePort ? port : null
})
github heroku / cli / packages / apps-v5 / src / commands / labs / info.js View on Github external
} else {
    print(feature)
  }
}

module.exports = {
  topic: 'labs',
  command: 'info',
  description: 'show feature info',
  args: [{ name: 'feature' }],
  flags: [
    { name: 'json', description: 'display as json' }
  ],
  needsAuth: true,
  wantsApp: true,
  run: cli.command(co.wrap(run))
}
github theburningmonk / lambda-coldstart-comparison / analyse-lang.js View on Github external
let lang = matchRes[1];
      let memorySize = parseInt(matchRes[2]);

      return {
        function: parts[0],
        lang: lang,
        memorySize: memorySize,
        value: parts[2]
      };
    });

  return rows;
});

let boxPlot = co.wrap(function*() {
  let rows = _.sortBy(yield readStats(), r => r.memorySize);

  let byLang = {
    csharp: { y: [], x: [], type: "box", boxpoints: "all", name: "csharp" },
    java:   { y: [], x: [], type: "box", boxpoints: "all", name: "java" },
    python: { y: [], x: [], type: "box", boxpoints: "all", name: "python" },
    nodejs6: { y: [], x: [], type: "box", boxpoints: "all", name: "nodejs6" },
    golang: { y:[], x: [], type: "box", boxpoints: "all", name: "golang"}
  }

  rows.forEach(row => {
    byLang[row.lang].y.push(row.value);
    byLang[row.lang].x.push(`${row.memorySize}MB`);
  });

  let data = _.values(byLang);