Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
New Twiddle
import Ember from 'ember';
import RSVP from 'rsvp';
//Make object proxy for promise
const ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);
/**
* Returns a computed property that combines all dependent
* promises into an RSVP hash, which when resolves, calls
* the async computed callback with each argument matching
* the dependent promise
*/
Ember.computed.async = function (...args) {
console.log('Async Computed Called');
// Remove computed function to call later
const func = args.pop();
const promiseNames = args.slice();
// Push a new computed handler onto the stack
args.push(function(...computedArgs) {
console.log('Computed function called');
// Get the promises
const promises = {};
promiseNames.forEach((promiseName) => {
promises[promiseName] = this.get(promiseName);
});
// Make hash of all promises
const rsvp = RSVP.hash(promises).then((resolved) => {
console.log('Promises complete', resolved);
const results = [];
promiseNames.forEach((name) => {
results.push(resolved[name]);
});
return func.apply(this, results);
});
return ObjectPromiseProxy.create({
promise: rsvp,
});
});
return Ember.computed.apply(null, args);
};
export default Ember.Controller.extend({
appName: 'Ember Twiddle Async Computed Properties',
asyncComputed: Ember.computed.async('model.promise1', function(model) {
return model;
}),
asyncComputed2: Ember.computed.async('model.promise1', 'model.promise2', function(model1, model2) {
return model1 + ' & ' + model2;
}),
});
import Ember from 'ember';
function makePromise(name, time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(name);
}, time);
});
}
export default Ember.Route.extend({
model() {
// This simulates an async promise
// Return a POJO so loading template doesn't kick in
return {
promise1: makePromise('Alex', 1000),
promise2: makePromise('Oli', 2000)
};
}
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
Async depending upon 1 promise:
{{#if asyncComputed.isPending}}
pending
{{else}}
{{asyncComputed.content}}
{{/if}}
<br />
<br />
Async computed depending upon 2 promises:
{{#if asyncComputed2.isPending}}
pending
{{else}}
{{asyncComputed2.content}}
{{/if}}
{
"version": "0.11.0",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.10.2",
"ember-data": "2.11.0",
"ember-template-compiler": "2.10.2",
"ember-testing": "2.10.2"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.