4 ms·
This is tangential to the discussion, here, but if you want to make 3 simultaneous async requests, it's super easy with promises. Here's an example using bluebi
by jclem 12y ago
This is tangential to the discussion, here, but if you want to make 3 simultaneous async requests, it's super easy with promises. Here's an example using bluebird (https://github.com/petkaantonov/bluebird https://github.com/petkaantonov/bluebird):
Promise.all([async1, async2, async3]).then(function(results) {
console.log('async1:', results[0]);
console.log('async2:', results[1]);
console.log('async3:', results[2]);
});
or:
Promise.all([async1, async2, async3]).spread(function(res1, res2, res3) {
console.log('async1:', res1);
console.log('async2:', res2);
console.log('async3:', res3);
});
With the co library (https://github.com/visionmedia/co https://github.com/visionmedia/co), it'd look like this:
co(function*() {
var results = yield [async1, async2, async3];
console.log('async1:', results[0]);
console.log('async2:', results[1]);
console.log('async3:', results[2]);
})();
Until ES6 is available everywhere, the existing promises libraries are so mature and easy-to-use that I don't really see a problem with them. Bluebird will even promisify an entire module for you with `promisifyAll`, so mixing it with callback-based modules is typically trivial.
I think that even though it relies on the use of third-party libraries like co, the generators solution is much easier to reason about than the proposed solution here.
I can't find the source, unfortunately, but I remember reading somewhere that generators were actually designed with this use case in mind, so the claim that using them for async "requires hacking a language feature that was designed for an entirely different use-case" is false, if I'm remembering correctly.
- vkjv 12y agoPromisifyAll is awesome... until you realize some code you are using is doing some seriously crazy stuff. For example, Mongoose takes all of methods on the prototype during object creation and replaces them with ones that run middleware. This means that if you try to use one of the promisified methods, none of the middleware gets called.
- jclem 12y agoI've never had that problem. My recommendation would be to not use it on Mongoose objects, then.
- esailija 12y agoI made a fix for a mongoose issue that sounds like what you describe and landed it in 1.2.3[1]. Can you verify? And if what you describe is a different issue can you make a github issue? (or is mongoose doing something so crazy that it cannot be helped at all? :P) [1] https://github.com/petkaantonov/bluebird/commit/70f90c33dd944a54d2995ed41f08860cc414f824 https://github.com/petkaantonov/bluebird/commit/70f90c33dd94...