How to use the method function from bluebird

Find comprehensive JavaScript bluebird.method code examples handpicked from public code repositorys.

In the Bluebird library for JavaScript, the method function is used to create a new function that returns a Promise for a specified method of an object.

2
3
4
5
6
7
8
9
10
var debug = require('debug');

module.exports = {

  // Returns a promise that will be resolved with an array of open ports
  test: bluebird.method(function(port, iface, callback) {
    var that = this;
    var log = debug('portastic:test');
    var def = bluebird.defer();
fork icon8
star icon76
watch icon1

+ 5 other calls in file

102
103
104
105
106
107
108
109
110
111
  };
}

util.inherits(MockConnection, Connection);

MockConnection.prototype.connect = Bluebird.method(function connect() {
  if (this.mockOptions.failConnect)
    throw new errors.ConnectionError(this.options.user, this.options.hostname);
  return this;
});
fork icon8
star icon6
watch icon2

How does bluebird.method work?

bluebird.method is a function in the Bluebird library for JavaScript that creates a new function that returns a Promise for a specified method of an object.

When bluebird.method is called with an object and a method name as input, it performs the following operations:

  • It creates a new function that accepts arguments for the specified method.
  • When the new function is called, it calls the specified method on the input object with the provided arguments.
  • It returns a Promise that resolves to the return value of the specified method, or rejects with an error if the method throws an exception.

By using bluebird.method, developers can create Promise-based versions of methods on objects, which can be useful for working with asynchronous code or integrating with other Promise-based APIs. This function can be used in a wide variety of situations, from creating Promise-based versions of existing methods to wrapping asynchronous functions with Promise support. Note that bluebird.method may not work as expected with certain types of objects or methods, so it is important to test thoroughly before using it in production code.

11
12
13
14
15
16
17
18
19
20
        BaseGame.call(this, position, tags);
        this.arbiter = arbiter;
}

Game.prototype.move
        = Promise.method(wrap(Game.prototype.move, function (move, moveNotation) {
        move.call(this, moveNotation);
        return this.arbiter.move({
                gameId: this.tags.gameId,
                moveNotation: moveNotation
fork icon0
star icon2
watch icon0

+ 33 other calls in file

555
556
557
558
559
560
561
562
563
564
565


test('Promise.method -> return value', function (t) {
  t.plan(4)
  twice(function () {
    var trans = ins.startTransaction()
    Promise.method(function () {
      return 'foo'
    })().then(function (result) {
      t.strictEqual(result, 'foo')
      t.strictEqual(ins.currTransaction().id, trans.id)
fork icon1
star icon0
watch icon1

+ 5 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const Promise = require("bluebird");

// Creating a Promise-based version of the Array.prototype.reduce method
const reduceAsync = Promise.method(Array.prototype.reduce);

// Using the Promise-based version of the method
const sum = reduceAsync([1, 2, 3], (acc, val) => acc + val, 0);

sum.then((result) => {
  console.log(result); // Outputs: 6
});

In this example, we're using bluebird.method to create a Promise-based version of the Array.prototype.reduce method, which is a built-in method for reducing an array to a single value. The Promise-based version of the method, reduceAsync, can be called with an array, a reduce function, and an initial value, and it will return a Promise that resolves to the reduced value. Note that in this example, we're passing the Array.prototype.reduce method directly to bluebird.method, which creates a Promise-based version of the method without requiring any additional code.

784
785
786
787
788
789
790
791
792
793
 *   {@link Collection#updatePivot updatePivot} calls.
 * @param {mixed|null} The ids of the models to attach, detach or update.
 * @param {object} [options] Query options.
 * @return {Promise}
 */
_handler: Promise.method(function(method, ids, options) {
  const pending = [];
  if (ids == null) {
    if (method === 'insert') return Promise.resolve(this);
    if (method === 'delete') pending.push(this._processPivot(method, null, options));
fork icon0
star icon1
watch icon1

+ 15 other calls in file

53
54
55
56
57
58
59
60
61
62
63
64
const hookWrapper = fn => {
  if (fn.length > 1) {
    return Promise.promisify(fn);
  }


  return Promise.method(fn);
};


/**
 * @param {Function[]} stack
fork icon0
star icon0
watch icon1

+ 9 other calls in file

307
308
309
310
311
312
313
314
315
316
withTimeoutRetry(func) {
  let attemptCount = 0;
  return new Promise((resolve, reject) => {
    function attempt() {
      if (attemptCount++) console.log(`syzoj.utils.withTimeout(): attemptCount = ${attemptCount}`);
      Promise.method(func)().timeout(5000)
      .then(resolve)
      .catch(Promise.TimeoutError, attempt)
      .catch(reject);
    }
fork icon0
star icon0
watch icon1

+ 9 other calls in file

85
86
87
88
89
90
91
92
93
94

function load_begin() {
    const t = ++token;

    out.is_loading = true;
    return Promise.method(fn)(out.reactive).then(load_succeed).catch(load_failed).finally(load_finished);

    function load_succeed(response) {
        if (t !== token) {
            return;
fork icon0
star icon0
watch icon2

+ 5 other calls in file

10
11
12
13
14
15
16
17
18
19
describe('post', () => {
  const Hexo = require('../../../lib/hexo');
  const baseDir = pathFn.join(__dirname, 'post_test');
  const hexo = new Hexo(baseDir);
  const post = require('../../../lib/plugins/processor/post')(hexo);
  const process = Promise.method(post.process.bind(hexo));
  const pattern = post.pattern;
  const source = hexo.source;
  const File = source.File;
  const PostAsset = hexo.model('PostAsset');
fork icon0
star icon0
watch icon1

+ 3 other calls in file

228
229
230
231
232
233
234
      });
      throw e;
    });
}


module.exports = Promise.method(groupCreationService);
fork icon0
star icon0
watch icon0

+ 11 other calls in file

31
32
33
34
35
36
37
38
39
40
41
42
  } else {
    return invitesService.resolveEmailAddress(invitingUser, type, externalId);
  }
}


var findEmailAddress = Promise.method(_findEmailAddress);


function findInvitationInfo(invitingUser, type, externalId, emailAddress) {
  var userToInvite;
  return invitesService
fork icon0
star icon0
watch icon0

+ 3 other calls in file

51
52
53
54
55
56
57
58
59
60
61
62
});


/**
 * Delete a token
 */
var deleteAuthToken = Promise.method(function(authCookieValue) {
  debug('Delete auth token: token=%s', authCookieValue);


  /* Auth cookie */
  if (!authCookieValue) return;
fork icon0
star icon0
watch icon0

+ 2 other calls in file

171
172
173
174
175
176
177
178
179
180
181
182
    .read(mongoReadPrefs.secondaryPreferred)
    .stream()
    .pipe(new BatchStream({ size: 4096 }));
}


var bulkUpdate = Promise.method(function(updates) {
  if (!updates || !updates.length) return;


  var bulk = persistence.TroupeUser.collection.initializeUnorderedBulkOp();

fork icon0
star icon0
watch icon0

191
192
193
194
195
196
197
198
199
200
201
  authCallback = undefined
  openExternalAttempted = false
  authRedirectReached = false
}


const _launchNativeAuth = Promise.method((loginUrl, sendMessage) => {
  const warnCouldNotLaunch = () => {
    if (openExternalAttempted && !authRedirectReached) {
      sendMessage('warning', 'AUTH_COULD_NOT_LAUNCH_BROWSER', loginUrl)
    }
fork icon0
star icon0
watch icon0

34
35
36
37
38
39
40
41
42
43
44
 * Returns the identity or null if the user doesn't have the
 * requested identity
 *
 * @return {Promise} Promise of the identity
 */
var getIdentityForUser = Promise.method(function(user, provider) {
  if (!user) return null;


  var cachedIdentities = user._cachedIdentities;

fork icon0
star icon0
watch icon0

+ 11 other calls in file