vendredi 27 février 2015

Convert nested 'for' loops into a Promise, for a Promise? Nested Promises?

I have an array where the values are sequences separated by '/', and a 'mapSeries' Promise (helper function for serially iteration with mapping) that loops through each value within each of the sequences.


Right now, the statement starts with a nested 'for' loop that splits a sequence into strings, and then pushes these values to an empty array to hand off to the 'mapSeries' promise..


After testing, it turns out that this only works if the original array has one sequence because multiple sequences run in parallel.


How can this be written as a promise that runs serially for each sequence, and then serially for each element in the given sequence?


Here's the attempt at the for loop (works for a single sequence):



var sequences = ['one/two/three', 'alpha/beta'];
var elements = [];
for (i=0; i<sequences.length; i++) {
var series = sequences[i].split("/");
for (j=0; j<series.length; j++) {
elements.push(series[j]);
}
var items = mapSeries(elements, function(element) {
// do stuff with 'one', then 'two', then 'three'
// when done..next series
// do stuff with 'alpha', then 'beta'
})
elements = []; // reset elements array for next series
} // for sequences.length


And here's an attempt at a Promise (error at element.charAt..):



var sequences = ['one/two/three', 'alpha/beta'];
var elements = [];
var items = mapSeries(sequences, function(sequence) {
sequence = sequence.split("/");
return mapSeries(sequence, function(series) {
elements.push(series);
return elements;
}).then(function(elements) {
return mapSeries(elements, function(element){
var element = element.charAt(0).toLowerCase() + element.slice(1); // first letter lowercase
// do stuff with 'one', then 'two', then 'three'
// when done..next series
// do stuff with 'alpha', then 'beta'
});
});
elements = []; // reset elements array for next series
});


mapSeries helper function:



function mapSeries(things, fn) {
var results = [];
return Promise.each(things, function(value, index, length) {
var ret = fn(value, index, length);
results.push(ret);
return ret;
}).thenReturn(results).all();
}

Aucun commentaire:

Enregistrer un commentaire