JSFiddle - React, Tailwind, and code Playground
by gschutz
HTML
<script src="https://cdn.rawgit.com/kriskowal/q/v1.0.1/q.js"></script>
<script src="https://cdn.rawgit.com/lodash/lodash/3.10.1/lodash.js"></script>
JavaScript
'use strict';
function eachPromise(data, eachFn, end) {
//if (!data.length) {
// end.call(this);
//}
var dispatches = [];
function Dispatch(d, key, callback) {
this.data = d;
this.key = key;
this.callback = callback;
this.exec = function() {
this.callback.call(this, this.data, this.key, this.next.bind(this));
return this;
};
this.next = function() {
if (dispatches[this.key+1])
dispatches[this.key+1].exec();
else if (end)
end.call(this);
return this;
};
}
_.each(data, function(d, k) {
var disp = new Dispatch(d, k, eachFn);
dispatches.push(disp);
});
if (dispatches.length)
_.first(dispatches).exec();
}
var thingsToDo = ['1', '2', '3', '4'];
//eachPromise(thingsToDo, function(d, k, next) {
// setTimeout(function() {
// console.log('vomita '+500*(k+1));
// next();
// }, 500*(k+1));
//});
//// TESTE multiple Q.all
// we have a tree
var tree = {
id: 1,
children: [{
id: 2,
children: [{
id: 3,
children: []
},{
id: 4,
children: []
}]
},{
id: 5,
children: []
},{
id: 6,
children: [{
id: 7,
children: []
}]
}]
};
// we have a list with unknow elements
var firstDefer = Q.defer();
var list = [firstDefer.promise];
var nodes = [];
function create(node, parent) {
var deferred = Q.defer();
setTimeout(function() {
var elem = {id: node.id, parent: parent || null};
nodes.push(elem);
deferred.resolve(elem);
}, 200 * _.random(1,5));
return deferred.promise;
}
// we have a recursively method that update list
function rec(node, parent, end) {
var deferred = Q.defer();
create(node, parent).then(function(n) {
console.log(n);
if (!node.children.length) {
deferred.resolve(node);
...