How to use bluebird - 10 common examples

To help you get started, we’ve selected a few bluebird 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 untu / comedy / test / typescript / test-clustered-actor.ts View on Github external
it('should not send messages to crashed forked actors', async function () {
      // Define test behaviour.
      let def = {
        kill: () => {
          process.exit(1);
        },

        getPid: () => process.pid
      };

      // Create clustered forked actor.
      let actor = await rootActor.createChild(def, {mode: 'forked', clusterSize: 2});

      // Get child actor PIDs.
      let pids = await P.map(_.range(2), () => actor.sendAndReceive('getPid'));

      // Kill first child.
      await actor.send('kill');

      // Wait for child to die.
      await tu.waitForCondition(() => !isRunning(pids[0]));

      // Send getPid message again. Second PID should be received.
      let pid2 = await actor.sendAndReceive('getPid');

      expect(pid2).to.be.equal(pids[1]);

      // Send getPid message again. First actor should be skipped as crashed.
      let pid = await actor.sendAndReceive('getPid');

      expect(pid).to.be.equal(pids[1]);
github LiskHQ / lisk-sdk / test / unit / sql / rounds.js View on Github external
it('should calculate rewards for round 1 correctly - all should be the same (native, rounds_rewards, delegates)', function () {
			var round = 1;
			var expectedRewards;

			return Promise.join(getBlocks(round), getRoundRewards(round), getDelegates(), function (blocks, rewards, delegates) {
				// Get expected rewards for round (native)
				expectedRewards = getExpectedRoundRewards(blocks);
				// Rewards from database table rounds_rewards should match native rewards
				expect(rewards).to.deep.equal(expectedRewards);

				expect(delegates_state[outsider_pk].blocks_missed_cnt).to.equal(1);
				return Promise.reduce(delegates, function (delegates, d) {
					if (d.fees > 0 || d.rewards > 0) {
						// Normalize database data
						delegates[d.pk] = {
							pk: d.pk,
							fees: Number(d.fees),
							rewards: Number(d.rewards)
						}
					}
					return delegates;
github untu / comedy / test / test-clustered-actor.js View on Github external
mode: 'forked',
      clusterSize: 3,
      balancer: 'CustomBalancer'
    });

    let error;

    yield parent.sendAndReceive('test', { shard: 0, value: 1 }).catch(err => {
      error = err;
    });

    expect(error).to.be.an.instanceof(Error);
    expect(error.message).to.match(/No child to forward message to./);
  }));

  it('should generate proper error if forward() returned non-existing child ID', P.coroutine(function*() {
    /**
     * Custom balancer.
     */
    class CustomBalancer {
      forward(topic, msg) {
        // Return absent ID.
        return '123456';
      }
    }

    // Define custom system with our test balancer.
    yield system.destroy();
    system = actors({
      test: true,
      balancers: [CustomBalancer]
    });
github oleksiyk / riakfs / test / siblings.js View on Github external
it.skip('file + file siblings without proper content', function () {
            var id;
            return Promise.promisify(fs.readFile)(f.path).then(function (data) {
                return riakfs.writeFile('/' + path.basename(f.path), data);
            })
            .then(function () {
                return riakfs.stat('/' + path.basename(f.path)).then(function (stats) {
                    id = stats.file.id;
                });
            })
            .then(function () {
                // make several siblings
                return Promise.map([0, 123, 456, 789], function (len) {
                    return riakfs.riak.put({
                        bucket: riakfs.filesBucket,
                        key: '/' + path.basename(f.path),
                        content: {
                            value: JSON.stringify({
                                id: uid2(32),
github epochtalk / core / tests / keys.js View on Github external
// 2 board last thread title
        // 2 board post count
        // 2 board thread count
        // 2 board total post count
        // 2 board total thread count
        // post post order
        // thread first post id
        // thread last post created at
        // thread last post username
        // thread post count
        // thread order
        // thread title
        // thread username
        // view count
        metadata.should.have.length(25);
        return Promise.map(metadata, function(data) {
          return probe.del(METADATA, data.key);
        });
      });
    });
github appium / appium-android-driver / test / functional / commands / keyboard / keyboard-e2e-specs.js View on Github external
async function clearKeyEvents (driver) {
  let el = await getElement(driver, BUTTON_CLASS);
  driver.click(el);

  // wait a moment for the clearing to occur, lest we too quickly try to enter more text
  await B.delay(500);
}
github selsamman / amorphic / test / postgres / amorphic.js View on Github external
// and semotus tries to send back a sync: false messages to force the client to refresh we handle
                // it ourselves and end the test.  Note that for whaever reason the implementation of XMLHTTPRequest
                // used here doesn not handle overlapping calls properly.  It will send the second call but will
                // never see the response for the inner call.  For this reason the full reset sequence never happens.
                var ServerRemoteObjectTemplate = serverController.__template__.objectTemplate;
                var oldSendMessage = ServerRemoteObjectTemplate._getSession().sendMessage;
                ServerRemoteObjectTemplate._getSession().sendMessage =  function (message) {
                    oldSendMessage.call(ServerRemoteObjectTemplate, message);
                    expect(message.sync).to.equal(false);
                    expect((new Date()).getTime() > (startTime + 5000));
                    done();
                };
            }).catch(function(e) {
                done(e);
            });
        Bluebird.delay(100).then(function () {
            RemoteObjectTemplate._getSession().sendMessageEnabled = true; // Force duplicate message
            clientController.mainFunc()
                .then(function () {
                    expect('Should not be here').to.equal(false);
                }, function (e) {
                    expect('Should not be here').to.equal(false);
                }).catch(function(e) {
                    done(e);
                });
        });
    });
github pmarkert / hyperpotamus / test / mock_context.js View on Github external
function processAction(action, context) {
		if (_.isArray(action)) {
			// Loop through each response validation step and verify
			return Promise.mapSeries(action, single_action => processAction(single_action, context));
		}
		context.processed_actions.push(action);
		if (action === true) {
			return Promise.resolve(true);
		}
		if (action === false) {
			return Promise.reject(exports.expected_failure);
		}
		throw new Error("Action type has not been implemented for mock-context");
	}
github HelpAssistHer / help-assist-her / server / data-import / test-data.js View on Github external
const Log = require('log')
const mongoose = require('mongoose')
const P = require('bluebird')

const PregnancyCenterModel = require('../pregnancy-centers/schema/mongoose-schema')
const pregnancyCenterSchemaJoi = require('../pregnancy-centers/schema/joi-schema')

const UserModel = require('../users/schema/mongoose-schema')
const PersonModel = require('../persons/schema/mongoose-schema')
const PregnancyCenterHistoryModel = require('../pregnancy-center-history/schema/mongoose-schema')

mongoose.Promise = require('bluebird')
const log = new Log('info')

// TODO: Error handling
const startDatabase = P.coroutine(function* startDatabase() {
	yield mongoose.connect(config.mongo.connectionString)

	log.info('Connected to database')
})

startDatabase()

async function reimport() {
	await PregnancyCenterModel.collection.drop()
	await UserModel.collection.drop()
	await PregnancyCenterHistoryModel.collection.drop()
	await PersonModel.collection.drop()

	const user = await UserModel.create({
		providerId: '10155647416405110',
		updatedAt: '2017-08-26 14:14:03.553',
github Jense5 / consultant-cli / src / add.js View on Github external
* @author  Jensen Bernard
 * @version 0.2.0
 */

import fs from 'fs';
import path from 'path';
import Promise from 'bluebird';
import validURL from 'valid-url';
import { exec } from 'child_process';

import content from './content';

// eslint-disable-next-line no-console
const info = console.info;

const execute = Promise.promisify(exec);

const name = (uri: string): string => path.basename(uri, '.git');
const folder = (uri: string, base: string): string => path.resolve(base, name(uri));
const canCreate = (uri: string, base: string): boolean => fs.existsSync(folder(uri, base));

const cmd = (uri: string, out: string): string => `git clone ${uri} ${out}`;
const clone = (uri: string, tmpl: string): Promise<> => execute(cmd(uri, folder(uri, tmpl)));

const add = (uri: string, templates: string): Promise<> =>
  new Promise((resolve, reject) => {
    if (validURL.isWebUri(uri)) {
      if (canCreate(uri, templates)) {
        clone(uri, templates).then(resolve).catch(reject);
      } else { info(content.duplicateName()); }
    } else {
      info(content.invalidURI());