JSFiddle - React, Tailwind, and code Playground
by escapedcat
JavaScript
/*
http://stackoverflow.com/a/24586168/1667461
var readFiles = function(files) {
var p = Q(); // Promise.resolve() without Q
files.forEach(function(file){
p = p.then(function(){ return readFile(file); }); // or .bind
});
return p;
};
but what if we need to get something back form the readFile function?
*/
function getColor(color) {
return new Promise(function(resolve, reject) {
var randomDelay = Math.random() * 100;
window.setTimeout(function() {
console.log('resolved: ', color, randomDelay);
resolve('got: ' + color);
}, randomDelay);
});
}
var colorArray = ['blue', 'green', 'red'];
var gotCol = [];
/*
cool, i understand this:
*/
var getColors = function(items, acc) {
//var p = Q(); // Promise.resolve() without Q
var p = Promise.resolve();
items.forEach(function(item){
console.log('c', item);
p = p.then(function(){ return getColor(item); });
acc.push(p);
});
return p;
};
getColors(colorArray, gotCol);
window.setTimeout(function() { console.log(gotCol) }, 2000);
/*
but what about the reduce example form the stackoverflow question:
var readFiles = function(files) {
return files.reduce(function(p, file) {
return p.then(function(){ return readFile(file); });
},Q()); // initial
};
*/
/*
would it be like this? this doesn't work. my brain stops working anyways:
var getColors = function(items) {
return files.reduce(function(p, item) {
return p.then(function(){ return getColor(item); });
}, Promise.resolve([])); // initial
};
*/