Skip to content

Instantly share code, notes, and snippets.

@sukima
Last active October 7, 2016 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sukima/b70fb091bde9d62999cd505c2dd666c6 to your computer and use it in GitHub Desktop.
Save sukima/b70fb091bde9d62999cd505c2dd666c6 to your computer and use it in GitHub Desktop.
e-c status trackers
import Ember from 'ember';
import { task, timeout, allSettled } from 'ember-concurrency';
const { Controller, get, set } = Ember;
function randomOutcome() {
if (Math.random() >= 0.5) {
throw new Error('fake error');
}
}
export default Controller.extend({
sampleData: [
Ember.Object.create({id: 1, word: 'foo'}),
Ember.Object.create({id: 2, word: 'bar'}),
Ember.Object.create({id: 3, word: 'baz'}),
Ember.Object.create({id: 4, word: 'foobar'}),
Ember.Object.create({id: 5, word: 'foobaz'}),
Ember.Object.create({id: 6, word: 'bazfoo'})
],
status: 'Nothing has started yet.',
childTask: task(function * () {
try {
yield timeout(3000);
randomOutcome();
} catch (error) {
get(this, 'errors').pushObject(error);
throw error;
}
}).maxConcurrency(2).enqueue(),
parentTask: task(function * () {
let childTask = get(this, 'childTask');
let data = get(this, 'sampleData');
let childTasks = data.map(sample => childTask.perform());
set(this, 'pendingTasks', childTasks);
set(this, 'errors', []);
set(this, 'status', 'Waiting for child tasks.');
yield allSettled(childTasks);
set(this, 'status', 'All child tasks are done.');
}).drop()
});
<button onclick={{perform parentTask}}>Click</button>
<p>
{{status}}
{{#if parentTask.isIdle}}
{{#if errors}}
<strong>
There were {{errors.length}} errors.
</strong>
{{/if}}
{{/if}}
</p>
<hr>
<table>
<thead>
<tr>
<th>ID</th>
<th>Word</th>
<th>Task Status</th>
</tr>
</thead>
<tbody>
{{#each sampleData as |data index|}}
<tr>
<td>{{data.id}}</td>
<td>{{data.word}}</td>
<td>{{task-status task=(get pendingTasks (concat index))}}</td>
</tr>
{{/each}}
</tbody>
</table>
{{#if task.isRunning}}
{{#if task.hasStarted}}
Started
{{else}}
Waiting
{{/if}}
{{else if task.error}}
!! {{task.error}}
{{else if task.isFinished}}
Done
{{else}}
Not started yet
{{/if}}
{
"version": "0.10.5",
"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.6.0",
"ember-data": "2.6.0",
"ember-template-compiler": "2.6.0",
"ember-testing": "2.6.0"
},
"addons": {
"ember-concurrency": "0.7.10"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment