bigeasy / cadence

A Swiss Army asynchronous control flow function for JavaScript.
https://bigeasy.github.io/cadence
MIT License
35 stars 7 forks source link

async.splat and async.hash #341

Closed allspiritseve closed 8 years ago

allspiritseve commented 8 years ago

This PR is a proof of concept for async.splat and async.hash. I'm totally open for discussion on their usefulness and alternate implementations.

async.splat

Used in place of an empty array in order to gather multiple return values from a step into a single array to be passed to the next step. Not strictly needed (obviously [] is more succinct) but I think it is more explicit.

async.hash

Inspired by Ember's RSVP.hash, async.hash accepts an object where each value is a step, and returns an object with the first return value of each step as its values. I opted to ignore multiple return values as it seemed more useful than always returning an array or somehow trying to guess whether the user wanted a single value returned or a single-item array.

allspiritseve commented 8 years ago

@bigeasy just noticed my formatting doesn't match the rest of cadence; I will fix that up later today.

allspiritseve commented 8 years ago

@bigeasy I'm no longer convinced async.hash belongs in cadence. Promises in Ember only return one successful value, in which case returning a hash is more useful than an array:

// model = results of Ember.RSVP.hash()
setController: function(controller, model) {
  this.set('list', model.list);
  this.set('tasks', model.tasks);
}

// model = results of Ember.RSVP.all()
setController: function(controller, model) {
  this.set('list', model[0]);
  this.set('tasks', model[1]);
}

However, in cadence, multiple values can be returned, so naming each result is effectively built-in:

async(function() {
  // make async() calls here...
}, function(one, two, three) {
  // do something with one, two, and three...
});

If someone wants a hash result, they can easily build one:

async(function() {
  async(function()
    // make async() calls here...
  }, function(one, two, three) {
    return [{ one: one, two: two, three: three }];
  });
}, function(hash) {
  // do something with hash...
});

Closing this PR.

bigeasy commented 8 years ago

I was going to propose making forEach and map work on hashes.

allspiritseve commented 8 years ago

@bigeasy sure, I could see that being useful.