1

I'm using the async module to help with creating an object that depends on other objects that are created asynchronously. The asynchronously created objects have validations that are ran against them that ultimately return a promise. The problem I'm having is that the "final" async callback seems to never be called and I cannot figure out why.

Example code:

function construct(self, opts) {
  async.parallel({
    venue: function(callback) {
      new Venue(opts.venue).then(function(venue) {
        callback(null, venue);
      }).catch(function(err) {
        callback(err);
      });
    },
    artists: function(callback) {
      new Artist(opts.artist).then(function(artist) {
        callback(null, artist);
      }).catch(function(err) {
        callback(err);
      });
    },
    function(err, res) {
      console.log(res);  // THIS IS NEVER CALLED.
    }
}
2
  • 1
    Is there a reason for mixing promises and async/callbacks? Generally it's better to pick one and stick to it. Commented Aug 8, 2014 at 19:05
  • 2
    It's really, really weird to have the new operator return a promise instead of the constructed object. If nothing else, you should probably change this to a factory function instead of a constructor. Commented Aug 8, 2014 at 19:37

1 Answer 1

2

It looks like the issue is that your callback function is inside the object that you're passing to async.parallel instead of as its own argument.

You've got

 async.parallel({
      venue: func,
      artists: func,
      callback
 })

Instead of

async.parallel({
      venue: func,
      artists: func,
      }, callback
);

BUT, it's really worth questioning what you gain from mixing promises and async like this; they're essentially designed to accomplish the same task; it'd probably be worth picking one or the other. Something like Promise.all or Promise.join is an alternative to async.parallel.

Pure promise version of this would look like: (this is assuming bluebird promises; but other libraries would be similar, if not identical)

Promise.join(new Venue(opts.venue), new Artists(opts.artists))
.then(function(venues, artists) {
    //
});

That's a lot cleaner, I think.

Sign up to request clarification or add additional context in comments.

1 Comment

I mistyped the example code. In my actual implementation, the final callback function is outside the initial object. I hadn't thought of the pure Promise approach. I'll give that a try. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.