Skip to content

Instantly share code, notes, and snippets.

@mwpastore
Last active September 28, 2017 22:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwpastore/34c4c4acfe2814f5265eea4158524b9a to your computer and use it in GitHub Desktop.
Save mwpastore/34c4c4acfe2814f5265eea4158524b9a to your computer and use it in GitHub Desktop.
Promise-aware compute macros
import computed from 'ember-macro-helpers/computed';
import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
import { typeOf } from '@ember/utils';
import { all } from 'rsvp';
export default function(Proxy) {
const PromiseProxy = Proxy.extend(PromiseProxyMixin);
return function(...dependentKeys) {
let callback = value => value;
if (typeOf(dependentKeys[dependentKeys.length - 1]) === 'function') {
callback = dependentKeys.pop();
}
return computed(...dependentKeys, function(...promises) {
const promise = all(promises)
.then(values => callback.apply(this, values));
return PromiseProxy.create({ promise });
});
};
}
import buildComputedPromise from './-computed-promise';
import ArrayProxy from '@ember/array/proxy';
export default buildComputedPromise(ArrayProxy);
import buildComputedPromise from './-computed-promise';
import ObjectProxy from '@ember/object/proxy';
export default buildComputedPromise(ObjectProxy);
import Model from 'ember-data/model';
import { belongsTo, hasMany } from 'ember-data/relationships';
import computedPromiseArray from '../macros/computed-promise-array';
import computedPromiseObject from '../macros/computed-promise-object';
export default Model.extend({
foo: belongsTo(),
bars: hasMany(),
fooDerivative: computedPromiseObject('foo', (foo) => {
// foo is resolved here, not a promise of an object
}),
barsDerivative: computedPromiseArray('bars.[]', (bars) => {
// bars is resolved here, not a promise of an array
}),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment