How to use bluebird

Comprehensive bluebird code examples:

How to use bluebird.hasLongStackTraces:

2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
Promise.config = function(opts) {
    opts = Object(opts);
    if ("longStackTraces" in opts) {
        if (opts.longStackTraces) {
            Promise.longStackTraces();
        } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
            disableLongStackTraces();
        }
    }
    if ("warnings" in opts) {

How to use bluebird.noConflict:

How to use bluebird._peekContext:

2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
Context.create = createContext;
Context.deactivateLongStackTraces = function() {};
Context.activateLongStackTraces = function() {
    var Promise_pushContext = Promise.prototype._pushContext;
    var Promise_popContext = Promise.prototype._popContext;
    var Promise_PeekContext = Promise._peekContext;
    var Promise_peekContext = Promise.prototype._peekContext;
    var Promise_promiseCreated = Promise.prototype._promiseCreated;
    Context.deactivateLongStackTraces = function() {
        Promise.prototype._pushContext = Promise_pushContext;

How to use bluebird._async:

1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
"use strict";
module.exports = function(Promise, PromiseArray, apiRejection, debug) {
var util = _dereq_("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;


Promise.prototype["break"] = Promise.prototype.cancel = function() {
    if (!debug.cancellation()) return this._warn("cancellation is disabled");

How to use bluebird.execAsync:

5
6
7
8
9
10
11
12
13
14
if (!_.isArray(strs)) {
  strs = [strs]
}

return () => {
  return cp.execAsync('ps -fww')
  .call('toString')
  .then((psOutput) => {
    _.forEach(strs, (str) => {
      expect(psOutput, 'ps output').contain(str)

How to use bluebird.some:

703
704
705
706
707
708
709
710
711
712
  })
  var p2 = resolved('p2')
  var p3 = rejected('p3')
  var p4 = resolved('p4')

  Promise.some([p1, p2, p3, p4], 2).then(function (result) {
    t.deepEqual(result, ['p2', 'p4'])
    t.strictEqual(ins.currTransaction().id, trans.id)
  })
})

How to use bluebird.CancellationError:

32
33
34
35
36
37
38
39
40
41
})
.on('error', function(err) {
  reject(err);
})
.on('abort', function() {
  reject(new Promise.CancellationError());
})
.on('timeout', function() {
  reject(new Promise.TimeoutError());
});

How to use bluebird.longStackTraces:

181
182
183
184
185
186
187
188
189
190

// TODO: with bluebird 3, we can no longer switch between having and not having longStackTraces.
// We'd have to measure it in two different test runs. For now, can run this test with
// BLUEBIRD_DEBUG=1 environment variable.
//testPromiseLib(bluebird, 'bluebird (with long traces)',
//               function() { bluebird.longStackTraces(); },
//               { iters: 20000, reps: 3, expectedUs: isNode ? 0.3 : 1, fudgeFactor: 8});


function testRepeater(repeaterFunc, name, timingOptions) {

How to use bluebird.filter:

801
802
803
804
805
806
807
808
809
810
t.plan(4)
twice(function () {
  var trans = ins.startTransaction()
  var arr = [resolved(1), resolved(2), resolved(3), resolved(4)]

  Promise.filter(arr, function (value) {
    return value > 2
  }).then(function (result) {
    t.deepEqual(result, [3, 4])
    t.strictEqual(ins.currTransaction().id, trans.id)

How to use bluebird.rejected:

1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
module.exports = function(Promise) {
var TypeError = require('./errors.js').TypeError;


function apiRejection(msg) {
    var error = new TypeError(msg);
    var ret = Promise.rejected(error);
    var parent = ret._peekContext();
    if (parent != null) {
        parent._attachExtraTrace(error);
    }

How to use bluebird._makeSelfResolutionError:

4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
function Promise$_resolveFromThenable(y) {
    if (called) return;
    called = true;

    if (x === y) {
        var e = Promise._makeSelfResolutionError();
        if (originalPromise !== void 0) {
            originalPromise._attachExtraTrace(e);
        }
        resolver.promise._reject(e, void 0);

How to use bluebird.bind:

403
404
405
406
407
408
409
410
411
412
var obj = new Obj()
var n = obj.n = Math.random()

var p = resolved('foo')

p = Promise.bind(obj, p)

p.then(function (result) {
  t.strictEqual(this.n, n)
  t.strictEqual(result, 'foo')

How to use bluebird.cast:

5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724


        if (val === undefined && !(i in promises)) {
            continue;
        }


        Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
    }
    return ret;
}

How to use bluebird.TimeoutError:

35
36
37
38
39
40
41
42
43
44
        })
        .on('abort', function() {
          reject(new Promise.CancellationError());
        })
        .on('timeout', function() {
          reject(new Promise.TimeoutError());
        });
    });
  };
});

How to use bluebird._getDomain:

2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
};


},{}],9:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = _dereq_("./errors").Warning;
var util = _dereq_("./util");
var canAttachTrace = util.canAttachTrace;

How to use bluebird.race:

641
642
643
644
645
646
647
648
649
if (alarms.length > 0) {
  return alarms;
}

// wait for new alarm coming or timeout
const result = await Promise.race([
  delay(timeout * 1000),
  this.newAlarmEvent()
]);

How to use bluebird.OperationalError:

37
38
39
40
41
42
43
44
45
46
        console.log("testError called");
        //Throw an error, the remote Promise will be rejected with a RemoteError, trapped with .catch()
        //RemoteError.remote contains the remote error object
        throw new Error("err!");
        //or an OperationalError, rejected with a RemoteOperationalError, trapped with .error()
        //throw new Promise.OperationalError("err!");
}

var server = net.createServer(function (c) {
        remotepromise.instantiate(c, serverfns)

How to use bluebird.coroutine:

3565
3566
3567
3568
3569
3570
3571
3572
3573
3574

var result;
if (!implementsReturn) {
    var reason = new Promise.CancellationError(
        "generator .return() sentinel");
    Promise.coroutine.returnSentinel = reason;
    this._promise._attachExtraTrace(reason);
    this._promise._pushContext();
    result = tryCatch(this._generator["throw"]).call(this._generator,
                                                     reason);

How to use bluebird.Promise:

808
809
810
811
812
813
814
815
816
817
    };
  }());
case 6:
  promises = _context19.sent;
  _context19.next = 9;
  return _bluebird.Promise.all(promises).then(function (responses) {
    // Do something with responses
    // array of responses in the order of urls
    // eg: [ { resp1 }, { resp2 }, ...]
    setTimeout(function () {

How to use bluebird.reduce:

124
125
126
127
128
129
130
131
132
133
const state = context.api.getState();
const deployPath = selectors.modPathsForGame(state, GAME_ID)[modType];
const deploymentManifest = await util.getManifest(context.api, modType, GAME_ID);
const gameManifestFiles = deploymentManifest.files.filter(entry =>
  path.basename(entry.relPath).toLowerCase() === MOD_MANIFEST);
return Promise.reduce(gameManifestFiles, async (accum, manifest) => {
  try {
    const modName = await getModName(path.join(deployPath, manifest.relPath), 'Name');
    accum.push({ modName, modId: manifest.source });
  } catch (err) {

How to use bluebird.settle:

52
53
54
55
56
57
58
59
60
61
  });
}
else if (_.isObject(myRequests)) {
  var keys = _.keys(myRequests);

  return Promise.settle(wrapped).then(function(settledValues) {
    var resolved = _.zipObject(keys, getSettledValues(settledValues));
    return  Promise.resolve(resolved);
  });
}

How to use bluebird.TypeError:

1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
    var fn;
    if (obj != null) fn = obj[methodName];
    if (typeof fn !== "function") {
        var message = "Object " + util.classString(obj) + " has no method '" +
            util.toString(methodName) + "'";
        throw new Promise.TypeError(message);
    }
    return fn;
}

How to use bluebird.PromiseInspection:

4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
module.exports = function() {
var makeSelfResolutionError = function () {
    return new TypeError("circular promise resolution chain\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
    return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
    return Promise.reject(new TypeError(msg));
};

How to use bluebird.any:

918
919
920
921
922
923
924
925
926
    });
}


// Loop over reponses
Promise.any(macsP)
    // First machine with capacity, so use
    .then((availableMac) => {
        availableMac = JSON.parse(availableMac);

How to use bluebird.fromNode:

66
67
68
69
70
71
72
73
74
75
  throw err
} else {
  return readPackageTree(npm.localPrefix).then(
    id.computeMetadata
  ).then((tree) => {
    return BB.fromNode((cb) => {
      createShrinkwrap(tree, {
        silent,
        defaultFile: SHRINKWRAP
      }, cb)

How to use bluebird.defer:

5
6
7
8
9
10
11
12
13
14

// 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();

  // Callback handling
  def.promise
    .then(function(ports) {

How to use bluebird._SomePromiseArray:

1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
    var ret = new SomePromiseArray(promises);
    var promise = ret.promise();
    ret.setHowMany(1);

How to use bluebird.fromCallback:

203
204
205
206
207
208
209
210
211
212
213
exports.editFile = function (str) {
  var pattern = Path.join(os.tmpdir(),'XXXXXX.yaml');
  var tmpfile = mktemp(pattern);
  fs.writeFileSync(tmpfile, str);


  return Promise.fromCallback(function (promiseCb) {
    editor(tmpfile, function (code) {
      if (code !== 0)
        return promiseCb(Error('Editor closed with code ' + code));

How to use bluebird.default:

34
35
36
37
38
39
40
41
42
43
const ping_1 = __importDefault(require("./controllers/ping"));
const productController = __importStar(require("./controllers/product"));
const cors_1 = __importDefault(require("cors"));
const app = (0, express_1.default)();
const mongoURI = secrets_1.MONGODB_URI;
mongoose_1.default.Promise = bluebird_1.default;
mongoose_1.default
    .connect(mongoURI)
    .then(() => {
    console.log('Connected to MongoDB');