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.)
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