Giter VIP home page Giter VIP logo

bluebird's People

Contributors

alubbe avatar benjamingr avatar bjouhier avatar calvinmetcalf avatar cscott avatar floatdrop avatar hvrauhal avatar iarna avatar lddubeau avatar lextiz avatar lvivski avatar markstos avatar mgenware avatar mhamann avatar nornagon avatar oliversalzburg avatar overlookmotel avatar page- avatar patrickjs avatar petkaantonov avatar retsam avatar spion avatar strawbrary avatar sukima avatar tgriesser avatar vitaly-t avatar vladimirkosmala avatar wgottschalk avatar xaka avatar yonjah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bluebird's Issues

Bluebird will not work in Chrome Apps / Extensions

When attempting to use Bluebird in a Chrome App or Extension the following error is thrown:

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

This is because Chrome Apps and Extensions do not allow the use of eval or the Function constructor. More information can be found in this article.

Other promise libraries such as when do not make use of eval or the Function constructor. I don't know if this contributes to Bluebird's performance at all, but I think it may be worthwhile investigating the possibility of creating an alternate build for restricted environments.

TypeError: Cannot call method 'call' of undefined

Hi!

Getting the following error when using progress notifications:

bluebird/js/main/progress.js:53
                fn.call( this._receiverAt( i ), progressValue, promise );
                   ^
TypeError: Cannot call method 'call' of undefined

This code can replicate it (v0.10.11-4, Node: v0.10.21):

var Promise = require('bluebird');

function delay (ms) {
    return new Promise(function (v) {
        setTimeout(v, ms);
    });
}

function timeout (promise, time, message) {
    var tm = delay(time).then(function () {
        throw new Promise.TimeoutError(message || ("Operation timed out after " + time + " ms"));
    });

    return Promise.race([promise, tm]);
}

var deferred = Promise.defer();

var progress = 0;

var f = function() {

    progress += 10;

    deferred.progress(progress); // ---- this line triggers error

    if (progress == 100) {
        deferred.resolve()
    } else {
        f()
    }
}

timeout(deferred.promise, 2000)

f();

Promises returned from generators are not resolved automatically

In Q, if an async generator returns a promise, that promise is resolved and the resolved value is passed on. In Bluebird, the promise itself is passed along as the next value:

Q v1.0.0:

Q.async(function* () {
    return Promise.resolve("")
})()
.then(function (str) {
    alert(typeof str); // 'string'
})
.done();

Bluebird v0.11.6-1:

Promise.spawn(function* () {
    return Promise.resolve("");
})
.then(function (str) {
    alert(typeof str); // 'object'
});

The workaround in Bluebird is to yield on the promise before returning it:

Promise.spawn(function* () {
    return yield Promise.resolve("");
})
.then(function (str) {
    alert(typeof str); // 'string'
});

But that seems like an unnecessary extra step that could be avoided, and I think it goes against expectations coming from Promise.try(). Is this behavior intentional?

Unclear error: TypeError: fn must be a function

Hi,

I am trying to learn more on Promisses, by converting this code into promisses: https://github.com/sideshowcoder/canned/blob/master/canned.js#L164-L203

I have made a first try here: mulderp/canned@5f87b15

But running specs gives:

./node_modules/.bin/jasmine-node --captureExceptions spec
Exception loading: /Users/pmu/projects/github/canned/spec/canned.spec.js
[TypeError: fn must be a function]
TypeError: fn must be a function
    at Function.Promise$Promisify [as promisify] (/Users/pmu/projects/github/canned/node_modules/bluebird/js/main/promisify.js:226:15)
    at Object. (/Users/pmu/projects/github/canned/canned.js:146:32)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object. (/Users/pmu/projects/github/canned/spec/canned.spec.js:3:14)
    at Module._compile (module.js:456:26)
make: *** [test] Error 1
npm ERR! Test failed.  See above for more details.
npm ERR! not ok code 0

I guess, that https://github.com/sideshowcoder/canned/blob/master/canned.js#L103-L133 does not apply to the Node callback convention, but I can't find anything in the docs, nor understand exactly why it results into an error.

monadic flatMap

I believe ES6 promises is going to have a flatMap that does not do recursive flattening but instead flattens one level deep. it may also disable thenable assimilation on flatMap.

It would be nice to have something similar here.

configurable error handling

Is it possible to turn try { ... } catch off in the bluebird promise implementation ?

It would be nice if we could opt out of having the then handler wrapped in a try catch.

This would enable people to make different decisions about error handling opinions instead of going with the "defaults" promises/A+ choose.

add a method / document for Promise.RejectionError

The following pattern:

fs.readFileAsync("doesn't exist").catch(Promise.RejectionError, function(e) {
    console.log(e.toString());
});

Is really cool.

It might be nice to have a method for it

fs.readFileAsync("doesn't exist").orElse(function(e) {
    console.log(e.toString());
});

That way its both shorter and it can be documented!

How to wait for the promise is fulfilled?

I am write a validate function in which I have to make few async calls (promises) after those promises are fulfilled I need to return a value from the function. It's like a synchronous code but involved promises. Can you help me in how to make it working?

function validateData(input) {
  var valid = true;
  //Some normal checks on input
  if (input.data1 == null) { valid = false;}
  //Now promises
  promise = Promise.all([
    Products.findAsync(input.productid),
    Users.findAsync(input.userid)
  ]).spread(product, user) {
     if (product == null) { return false;}
     if (user == null) { return false; }
     return true;
  });
  //Here I want to get the promise fulfillment value and combine with the variable.

  return valid;
}

Please help me. I'm kind of stuck for last few days on it. I tried several ways like using setImmediate etc.. but no luck.

Thanks in advance,
-Kesav

How to migrate from Q.js?

I'm currently using Q.js and investigating bluebird.
Would be nice if i could just replace
var q=require("Q")
With
q=require("bluebird")

What should I expect?

Promise.promisify doesn't seem to work very well.

Hi, this might not be an issue - it may be me being stupid, but over on HN you asked me to post this here. Basically, I'm trying to use promisify to prevent having to do lots of pointless code.

So, to take something like this:

fs = require 'fs'

quietMakeDir = (dir) ->
    new Promise (resolve, reject) ->
        fs.mkdir(dir, ->
            resolve()
        )

quietMakeDir(dir).then(->
    resolve([created, url, path])
)

Into something like this...

fs = Promise.promisify(require 'fs')

fs.mkdir(dir).finally(->
    resolve([created, url, path])
)

But when I do this, I get the error:

/....coffee:102
          return fs.mkdir(dir)["finally"](function() {
                                               ^
TypeError: Cannot call method 'finally' of undefined
  at /....coffee:78:17, <js>:102:48
  at Object.cb [as oncomplete] (fs.js:168:19)

Basically, my actual script is here:

https://github.com/radiosilence/subdown/blob/node/subdown.coffee

And it would be appreciated if you could help me write this in the "best" way possible - do I really need to be creating promises from within so many methods?

Here's what happens if I do it from the Coffee cli:

% coffee                                      node•
coffee> Promise = require 'bluebird'
...
coffee> fs = Promise.promisify(require 'fs')
...
coffee> parp = fs.mkdir('hio')
undefined
coffee> 

nfcall, nfbind, nfapply ?

Good day.
I've seen through documentation and find mentioning that bluebird passes Q tests. So I've tried to look for nfcall / nfbind / nfapply, seemes nothing.
So my question is: what alternative should I use in bluebird (by design)?
As I only see is promisify, but it some cases it can work unproperly due to variable num of arguments of callback-style function. So in this case I prefer to use «manual» nf-functions.
Thanks.

interpreting `this` in .then()

The following code

var Promise = require('bluebird'),
  peter = {123: 456 };

  peter.print_this = function() {
    return console.log(this);
  };

  peter.print_this();
  Promise.delay(1000).then(peter.print_this);

produces

{ '123': 456, print_this: [Function] }

as it should. But then, after the delay, it shows that this is set to global instead of peter. Is this intentional (no pun intended)? How is this to be interpreted?

Browser support questions

Is there a list of browsers the library is known to work with, and if so could this be published in the readme?

Also, does the NFE use throughout the library cause potential memory-leak issues with older IE's (< 9)?

Promise.delay should allow numeric values that are not strictly integers

For compatibility with setTimeout both in browsers and in Node and with other promises library like Q and the Deferred object in the jQuery library I propose:

    Promise.delay(someValue);

To work with numbers that are not integers the same way browsers, other libraries and node would.

This would require changing:

       if ((ms | 0) !== ms || ms < 0) {
            return apiRejection("expecting a positive integer");
        } 

To

       if (typeof ms !== "number") {
            return apiRejection("expecting a number");
        }

For maintaining type safety but making interop with code that does delay(100*Math.random()) for example easier.

Ability to get a fresh copy of the library

Looking through the latest commits to modularize the code, I assume you're probably going for this, but just in case - I wanted to point out that it'd be nice if there were a way to get a fresh copy of the Promise object, for instance if you wanted to set a different Promise.onPossiblyUnhandledRejection for different objects (perhaps in different libraries)

It'd be nice if:

var Promise = require('bluebird');

would require ./src/bluebird.js, which would then have:

module.exports = require('./promise')();

and then if you wanted a unique copy of the bluebird Promise, you could do:

var OtherPromise = require('bluebird/js/main/promise')();

or something along those lines, as long as there aren't any performance issues that come along with allowing that.

Update the browser build to the latest PR

Hi Petka,

Can you update the builds to the latest version?

( we use them quite extensively and I fetch a fresh copy from gh often which brings the ff error)

I'd create a PR but that seems so silly.

Thanks

Cancel followed by Fulfill on same frame leads to Fulfillment

I was using the latest Master branch code and noticed something somewhat unexpected. Here is a test I wrote in my jasmine harness which passes, but seems like it should not pass:

        it("fulfill trumps cancel on the same frame", function () {
                var tuple = Promise.pending();
                var promise = tuple.promise;

                var rejected = false;
                var fulfilled = false;
                promise = promise.cancellable().then(function () {
                    fulfilled = true;
                    expect(rejected).toBe(false);
                }, function() {
                    rejected = true;
                });

                promise.cancel();
                tuple.fulfill();

                waitsFor(function () {
                    return fulfilled;
                }, "promise was not fulfilled correctly");
            });
        });

These tests also pass, which implies reject/fulfill ordering matters on the same frame. So it seems weird that cancel/fulfill ordering does not matter when it does for reject.

            it("fulfill trumps reject on the same frame when called first", function () {
                var tuple = Promise.pending();
                var promise = tuple.promise;

                var rejected = false;
                var fulfilled = false;
                promise = promise.then(function () {
                    fulfilled = true;
                    expect(rejected).toBe(false);
                }, function() {
                    rejected = true;
                });

                tuple.fulfill();
                tuple.reject();

                waitsFor(function () {
                    return fulfilled;
                }, "promise was not fulfilled correctly");
            });

            it("reject trumps full on the same frame when called first", function () {
                var tuple = Promise.pending();
                var promise = tuple.promise;

                var rejected = false;
                var fulfilled = false;
                promise = promise.then(function () {
                    fulfilled = true;
                }, function() {
                    rejected = true;
                    expect(fulfilled).toBe(false);
                });

                tuple.reject();
                tuple.fulfill();

                waitsFor(function () {
                    return rejected;
                }, "promise was not rejected correctly");
            });

Is there a by-design explanation for this or is this just how things happen to work due to cancel taking an extra tick to process?

Pros/cons of promisifyAll() considering only enumerable own properties

Continuing from #7, I'm still trying to get promisifyAll() working on Mongoose models. There is one more issue remaining, though. The "interesting" methods of Mongoose models reside in their prototypes, which breaks the "only enumerable own properties are considered" check:

if( callback.hasOwnProperty( key )

I actually wonder if this check is useful at all. It prevents promisifyAll() from working in valid use cases (e.g. Mongoose models), and removing it shouldn't break anything (even if an Async method is created for some unsuitable property, it wouldn't break until someone attempts to use it). For added safety, a different check could be added - whether an Async method with that name already exists (currently it would be overwritten).

Then is not called

I am experimenting with a small "Hello World" example using Bluebird, and showing the effect of execution time of operations. I use this:

greeting = {};
greeting.waitAndSay = function(delay, word) {
   return setTimeout(function() { console.log(word) }, delay) }


var Promise = require("bluebird");
Promise.promisifyAll(greeting);

greeting.waitAndSayAsync(1000, "hello")
             .then(function() { 
                         console.log("world");
                         return "world" });

But nothing in the Then callback gets evaluated. Any idea, if I miss something from the docs, or maybe a bug?

rejection turns into fulfillment

This has me puzzled, and I can't find justification for it in the Promise/A+ spec.

var r = Promise.pending();
r.promise.catch(Promise.CancellationError,
               function () { console.log("cancel"); })
         .then(function () { console.log("fulfilled"); });
r.cancel();

When I do the above I was expecting that I'd get "cancel" in the output, but I got "cancel" and "fulfilled".

It turns out this is because my rejection handler didn't return anything, so the return value of undefined was promoted into a fulfilled promise! I can't find anything in Promise/A+ that indicates this should happen. I would argue that if you don't return anything, the .then promise should take the state of the promise that triggered the .catch.

This would prevent a rejection from unexpectedly being converted to a fulfillment.

To work around the issue, I explicitly return Promise.rejected(reason) form the .catch callback, but this requires allocating a new promise. What I really want to say is 'just use the existing promise', but I don't see any way to do that.

Uncaught TypeError: Cannot read property '_fulfill' of undefined

I get the following error in some complex workflow but unfortunately can't replicate it with a simple example:

Uncaught TypeError: Cannot read property '_fulfill' of undefined
      at Promise$_resolveLast [as _resolveLast] (bluebird/js/main/promise.js:847:34)
      at Async$_consumeFunctionBuffer [as _consumeFunctionBuffer] (bluebird/js/main/async.js:63:12)
      at Async$consumeFunctionBuffer (bluebird/js/main/async.js:36:14)
      at process._tickCallback (node.js:415:13)

I was hoping it was related to #35 but its something different. Maybe you have some quick ideas? If not - I will keep trying to replicate it with example and paste it here.

Promise.try returning a Promise.

Since the performance work done to Promise.try in 28cfd04 it no longer works as expected, in that if a promise is returned to Promise.try then the promise returned by Promise.try will resolve to the returned promise object, not the resolved value of that promise.

To reproduce this you can check out http://jsfiddle.net/Y7qPH/ or use the following node.js code:

var Promise = require('bluebird');
Promise.try(function() {
    return Promise.fulfilled('Hello!');
}).then(function(value) {
    console.log(JSON.stringify(value));
});

Promise.coroutine() diverts exceptions

Testcase:

try {
    Promise.coroutine(function* () {
        throw new Error('Test Error');
    })();
} catch (err) { console.log('Caught'); }

The catch clause here has no effect. Instead, the thrown error escapes to the global "possibly unhandled" exception handler.

Is this the intended behavior?

Add receiver parameter for Promise.coroutine()

I need to be able to set the receiver parameter for Promise.coroutine() same as is available for Promise.promisify. But I want to check first - is there a reason why coroutine currently doesn't support such a parameter. If not I'd be happy to create a pull request.

Differentiating between thrown errors and rejected reasons

I want to differentiate between errors passed to the reject(err) function and those that are thrown.

So that I can do this

function doThing(arg) {
  return new Promise(function (resolve, reject) {
    if (typeof arg !== "string") return reject(new Error("invalid thing"));
  });
}

function doBuggyThing(arg) {
  return new Promise(function (resolve, rej) {
    // arg2 & reject dont exist. this is buggy.
    if (arg2 && typeof arg2 !== "string") return reject(new Error("invalid thing"));
  });
}

Promise.onPossiblyUnhandledRejection(function (err) {
  // gets called by doBuggyThing
});

doThing()
  .error(function (err) { /* oops forgot correct args */ })
  .done();

doBuggyThing()
  .error(function (err) { /* never called */ })
  .done();

Cannot use Promise.coroutine with Traceur compiled code

Problem is in promise_spawn.js:

var haveEs6Generators = (function(){
    try {
        /* jshint nonew: false */
        new Function("(function*(){})");
        return true;
    }
    catch(e) {
        return false;
    }
})();

Bluebird works fine with Traceur when I force this check to return true. I'm not sure what a better check would be, but some means of overriding this would be fine with me.

Naming standards

Hey, I just wanted to ask why the code does things like: Promise$_all Promise$_All and Promise$all?

Is the naming (lower case/upper case) here an important convention?

Can we rename these to something more meaningful?

Implement Promise.using

After having this discussion on IRC, making this a little more official.

Having a method allowing us to handle resource lifecycles is a pretty good idea, for any application communicating with a database for example.

It's basically the same concept as C#'s using or Java's try.

Here is the proposed syntax:

return Promise.using(getConnection(), function(connection) {
    return connection.query(fn).then(fn);
});

A naive (i.e. not fully working) implementation of this would be:

Promise.using = function(resource, fn) {
  // wraps it in case the resource was not promise
  var pResource = Promise.cast(resource);
  return pResource.then(fn).finally(function() {
    return pResource.then(function(resource) {
      return resource.close();
    });
  });
}

This means that we require the resource object to implement a close method, that will take care of freeing the resource. It's the same concept as Java requiring an AutoCloseable interface. The method can be dispose or whatever.

Thoughts?

not using setImmediate on browsers that support it.

deferFn only uses setImmediate for node (or more accurately if process and process.cwd are defined). For browsers such as IE and Chrome that support setImmediate, it would be preferable that bluebird uses it instead of the MutationObserver hack/workaround that it currently uses.

Expose promise in rejection handler (needed to implement report-on-GC)

Hey, I wrote a module for bluebird that defers possibly unhandled rejections until after the promise is collected by the GC :)

But it does require patching bluebird's code a bit:

diff --git a/src/promise.js b/src/promise.js
index 6b39a0d..e3a2f72 100644
--- a/src/promise.js
+++ b/src/promise.js
@@ -1679,7 +1679,7 @@ function Promise$_notifyUnhandledRejection( reason ) {
     if( !isHandled( reason[ERROR_HANDLED_KEY] ) ) {
         reason[ERROR_HANDLED_KEY] =
             withHandledMarked( reason[ERROR_HANDLED_KEY] );
-        CapturedTrace.possiblyUnhandledRejection( reason );
+        CapturedTrace.possiblyUnhandledRejection( reason, this );
     }
 };

Would this be an acceptable patch?

This is the entire actual module (requires weak from npm)

var weak = require('weak');
var Promise = require('bluebird');
var handler = null;

function report(e) { 
    return function() {
        if (typeof(handler) !== 'function') throw e; 
        else handler(e);
    }
}

function handle(e, p) { weak(p, report(e)); }

Promise.onPossiblyUnhandledRejection(handle);

exports.handler = function(f) { handler = f; }

should `reject` be bound to its promise?

I have lots of code like this:

stream.on('error', pending.reject.bind(pending));

Would it make sense for reject to be bound to its promise in the library? This is subjectively "cleaner".

stream.on('error', pending.reject);

.error() catches all errors from external libs

I mentioned this on IRC, but I'm also going to put it here, since I think its probably not possible to automatically deal with this one :(

var BB = require('bluebird');
var BB2 = require('bluebird/js/main/promise')(); 
BB.cast(1).then(function() { 
    return BB2.cast(1).then(function() { 
        return makes.reference.errors(); 
    }); 
}).error(function(e) { 
    console.log("This should not execute", e); 
});

This also occurs if I have a node module that depends on bluebird which I'm developing in parallel with the app that depends on it. For example, while developing anydb-sql and doxbee (which depends on anydb-sql), I can't use .error() in doxbee because that might also catch programmer errors within anydb-sql.

It gets slightly worse :( If I run npm dedupe (which is often done before browserifying or before pushing node_modules to production) the behavior of my program will change -- since now both modules will depend on the same instance of bluebird.

Anyway, in general, the assumption that an external promises-based module never has bugs is just too big -- too often this is not the case.

I realize that the situation with error types coming from most promise-based libraries is not so good, but I don't think automatic rejection marking is going to solve it -- so far it seems to be making some things worse :(

The easiest way out of this one is for promise users to settle on a flag, e.g. SomeError.prototype.isPromiseRejection = true, and for error() to all errors that have it. Then people can use create-error to make rejections

Automatic rejection marking should be possible, yes -- but opt-in, maybe via a method that converts the library in a similar manner that .promisify does that for callbacks.

What do you think?

Add .timeout() to promise instances?

Hi!

What do you think about adding .timeout() method to promise instances? I know there is a solution with .race but a dedicated method might be more convenient. Something like this (it doesn't work actually :) ):

Promise.prototype.timeout = function(ms, message) {
    var self = this;
    setTimeout(function() {
        self._reject(new Promise.TimeoutError(message || ("Operation timed out after " + ms + " ms")))
    }, ms)

    return this;
}

And maybe a Promise.delay() ? which is also very common (especially in tests):

Promise.delay = function (ms) {
    return new Promise(function (v) {
        setTimeout(v, ms);
    });
}

Bower installing a very old version (0.3.0)

I'm not sure if bluebird supports bower or not, but it's listed in the repository and attempting to install bluebird will install version 0.3.0.

bower search bluebird gives:

bluebird git://github.com/petkaantonov/bluebird.git

bower install bluebird gives:

bower bluebird#*            not-cached git://github.com/petkaantonov/bluebird.git#*
bower bluebird#*               resolve git://github.com/petkaantonov/bluebird.git#*
bower bluebird#*              download https://github.com/petkaantonov/bluebird/archive/v0.3.0.tar.gz
bower bluebird#*               extract archive.tar.gz
bower bluebird#*              resolved git://github.com/petkaantonov/bluebird.git#0.3.0

Nested map results in empty Array

Hi there,

I want to use nested promises to fetch a series of IDs from Redis first, and then map the the IDs to Redis records. So, I try:

  function allMovies() {
    return client.smembersAsync('movies.ids').map(function(id) {
      console.log(id);
        return client.hmgetAsync("movies:" + id, 
          'title', 
          'description', 
          'director', 
          'year',
          'rating'
          );
        }).map(function(data) {
          console.log(data);
           return {
                 id: id,
                 title: data[0], 
                 description: data[1], 
                 director: data[2],
                 year: data[3],
                 rating: data[4],
                 showtime: now() + id * 3600
               };
          });
  },

And then, I want to inspect the elements with:

> allMovies()
[object Object]
> allMovies().then(function(m) { console.log(m) })
[object Object]
> []

and

allMovies().toJSON()
{ isFulfilled: true,
  isRejected: false,
  fulfillmentValue: [],
  rejectionReason: undefined }

However, the version of the gist works: https://gist.github.com/mulderp/7045228

So, it is a bit confusing, maybe a bug.

Random String not printing correctly

I want to promisifyAll to generate a random string for password hashing, and I basically want to translate the exampled based on "when" to bluebird:

http://stackoverflow.com/questions/20281986/how-to-convert-an-array-of-bytes-into-string-with-node-js#20282065

However, it prints:

random byte string: undefined

when doing this:

var Promise          = require('bluebird');
var RandBytes     = require('randbytes');
var randomSource  = RandBytes.urandom.getInstance();

Promise.promisifyAll(randomSource);

get_rand = function() {
  return randomSource.getRandomBytesAsync(20)
    .then(function(bytes) {
      return bytes.toString('hex'); // convert to hex string
    })
    .catch(function(err) {
      console.log(err)
    });
}

// example call:
get_rand().then(function(bytes) {
  console.log('random byte string:', bytes);
});

While, the "when" library gives:

random byte string: 6a4ce9c86b638b891a364b16d029ff3370cb71d9

Am I missing something?

Use require and browserify

The src files are currently concatenated in the same closure instead of requiring each other due to V8 only implementing inlining across context boundaries for IA-32.

However, recently V8 has implemented this optimization for ARM and MIPS too and so I expect x64 will support it soon. After that there is no reason to concatenate everything under the same closure I imagine.

microbenchmark performance 100x slower

Quite a mystery but bluebird performs 100x worse in various microbenchmarks by @stefanpenner after introducing custom builds in 0.9.3

Before that commit:

bluebird def x 1,564,555 ops/sec ±1.67% (68 runs sampled)

After:

bluebird def x 20,000 ops/sec ±1.67% (68 runs sampled)

While this is a low quality benchmark such radical change still worries me:

//Async test
function make() {
  var resolver = Promise.pending()

    resolver.fulfill()

  return resolver.promise
}


make().then(function () { deferred.resolve() })

Only the node.js macrobenchmark are currently used to test for performance regressions so that's how these were missed.

Promise.promisify() doesn't work with 'function-objects'

Promise.promisify() tries to decide which overload to execute by performing the following check:

if( typeof callback === "object" && callback !== null ) {

This fails with some objects, which are also functions and thus their typeof is "function" instead of "object". Mongoose models are one example (I was trying to promisify an entire model when stumbling on this; promisifying individual methods works fine).

I think that promisify() shouldn't try to be too smart and auto-detect which overload should be executed. Instead, the version which operates on objects should be renamed to e.g. 'promisifyAll' or something like that.

Unfiltered Function.Promise$Pending in longStackTrace

Not sure if it should be filtered or not - if it shouldn't be you can just close it.

Example output:

Error: Failed!
    at /home/spion/Documents/blue-tape/test/index.js:42:15
From previous event:
    at Function.Promise$Pending [as pending] (/home/spion/Documents/blue-tape/node_modules/bluebird/js/bluebird.js:1349:13)
    at delay (/home/spion/Documents/blue-tape/test/index.js:7:22)
    at Test._cb (/home/spion/Documents/blue-tape/test/index.js:41:12)
From previous event:
    at Function.Promise$Pending [as pending] (/home/spion/Documents/blue-tape/node_modules/bluebird/js/bluebird.js:1349:13)
    at delay (/home/spion/Documents/blue-tape/test/index.js:7:22)
    at Test._cb (/home/spion/Documents/blue-tape/test/index.js:35:16)
From previous event:

...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.