Skip to content

Instantly share code, notes, and snippets.

@jamesarosen
Last active August 29, 2015 14:24
Show Gist options
  • Save jamesarosen/412bc3d8b04341b10283 to your computer and use it in GitHub Desktop.
Save jamesarosen/412bc3d8b04341b10283 to your computer and use it in GitHub Desktop.
A Promise-Aware Hash-Merging Function

I have a case in an Ember.Route where I want to start a few asynchronous fetches, each of which resolves with a complex Object, and then eventually merge the results. RSVP has some nice higher-level Promise utilities, but it doesn't have merge. So I wrote one.

If you only ever want to merge two Promises, you could do this

function mergeTwoPromises(promiseA, promiseB) {
  return new Ember.RSVP.Promise(function(resolve, reject) {
    Ember.RSVP.all([ promiseA, promiseB ])
    .then(function([ hashA, hashB ]) {
      resolve(Ember.merge(hashA, hashB));
    })
    .catch(reject);
  });
};

If you want to merge n Promises, you'll need

function mergeNPromises(...promises) {
  return new Ember.RSVP.Promise(function(resolve, reject) {
    Ember.RSVP.all(promises)
    .then(function(...hashes) {
      resolve($.extend(hashes));
    })
    .catch(reject);
  });
};

(Ember.merge only takes two arguments.)

Example

mergeNPromises({
  aPromiseThatResolvesWith({ foo: 'foo1', bar: 'bar1', baz: 'baz1' }),
  aPromiseThatResolvesWith({ foo: 'foo2', bar: 'bar2' }),
  aPromiseThatResolvesWith({ foo: 'foo3', quux: 'quux3' })
}).then(function(combined) {
  combined.foo;  // foo3
  combined.bar;  // bar2
  combined.baz:  // baz1
  combined.quux; // quux3
});

The above code is released under the Apache License v2.0, Copyright 2015 James A Rosen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment