How to use the bluebird.coroutine function in bluebird

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 / 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 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 nodeca / nodeca.core / lib / queue / lib / index.js View on Github external
}


  var task_id_local = task_id_global.substr((self.__prefix__ + worker.name + ':').length);
  var task = new Task(task_id_local, JSON.parse(taskData), worker, self);

  // Execute map without wait
  self.__doMap__(task, deadline);
});


// Move task from pending to mapping and run `map`
//
// - task_id_global (String) - the task ID
//
Queue.prototype.__consumeTask__ = Promise.coroutine(function* (task_id_global) {
  var self = this;

  // Get redis time and task options
  let data;

  try {
    data = yield self.__redis__.multi()
                     .time()
                     .hmget(task_id_global, 'data', 'type')
                     .exists(task_id_global)
                     .execAsync();
  } catch (err) {
    self.emit('error', err);
    return;
  }
github wikimedia / mediawiki-extensions-CirrusSearch / tests / integration / features / step_definitions / page_step_helpers.js View on Github external
waitForOperations( operations, log = null, timeoutMs = null ) {
		return Promise.coroutine( function* () {
			if ( !timeoutMs ) {
				timeoutMs = operations.reduce( ( total, v ) => total + ( v[ 0 ].match( /^upload/ ) ? 30000 : 10000 ), 0 );
			}
			const start = new Date();

			const done = [];
			const failedOps = ( ops, doneOps ) => ops.filter( ( v, idx ) => doneOps.indexOf( idx ) === -1 ).map( ( v ) => `[${v[ 0 ]}:${v[ 1 ]}]` ).join();
			while ( done.length !== operations.length ) {
				let consecutiveFailures = 0;
				for ( let i = 0; i < operations.length; i++ ) {
					const operation = operations[ i ][ 0 ];
					let title = operations[ i ][ 1 ];
					const revisionId = operations[ i ][ 2 ];
					if ( done.indexOf( i ) !== -1 ) {
						continue;
					}
github hellojwilde / node-safebrowsing / src / match / getFullHashResult.js View on Github external
var Promise = require('bluebird');
var MatchResultTypes = require('./MatchResultTypes');

var regeneratorRuntime = require('regenerator/runtime');

var getFullHashResult = Promise.coroutine(function*(cache, list, hashObject) {
  var hashResult = {
    list: list,
    resultType: null,
    hashObject: hashObject,
    metadata: {}
  };

  var hasDetails = yield cache.hasPrefixDetails(
    list.name, 
    hashObject.prefix
  );

  var isDetailMatch = yield cache.isPrefixDetailsMatch(
    list.name, 
    hashObject.prefix, 
    hashObject.hash
github novacrazy / bluebird-co / src / yield_handler.js View on Github external
/*
             * This is really annoying, as there is no possible way to determine whether `value` is an instance of
             * an Object, or is a class that extends Object, given Babel 6. It seems possible in Babel 5.
             * I'm not sure if this was an intentional change, but for the sake of forward compatibility, this will
             * consider anything that also inherits from Object as an object.
             * */

            if( constructor === Object || Object.isPrototypeOf( constructor ) ) {
                return objectToPromise.call( this, value, constructor );
            }
        }

    } else if( typeof value === 'function' ) {
        if( isGeneratorFunction( value ) ) {
            return Promise.coroutine( value ).call( this );

        } else {
            return thunkToPromise.call( this, value );
        }
    }

    /*
     * Custom yield handlers allow bluebird-co to be extended similarly to bluebird yield handlers, but have the
     * added benefit of working with all the other bluebird-co yield handlers automatically.
     * */
    for( let handler of coroutine.yieldHandlers ) {
        let res = handler.call( this, value );

        if( isThenable( res ) ) {
            return res;
        }
github novacrazy / scriptor / src / script.js View on Github external
return this.exports().then( main => {
                if( main !== null && main !== void 0 ) {

                    if( main['default'] ) {
                        main = main['default'];
                    }

                    if( typeof main === 'function' ) {
                        if( isGeneratorFunction( main ) ) {
                            main = Promise.coroutine( main );
                        }

                        return this._callWrapper( main, null, args );
                    }
                }

                return main;
            } );
github telemmo / telemmo / src / game / core / combat / index.js View on Github external
export function start (combat) {
  function* generate () {
    let state = combat
    while (!state.finishedAt) {
      state = yield turn(state, finish)
    }

    return state
  }

  return Promise.resolve()
    .then(Promise.coroutine(generate))
}