Any helper function with promise looping I have seen actually made it much worse than what you can do out of the box with recursion.
It is a little nicer with .thenReturn
but yeah:
function readFile(index) {
return new Promise(function(resolve) {
setTimeout(function() {
console.log("Read file number " + (index +1));
resolve();
}, 500);
});
}
// The loop initialization
Promise.resolve(0).then(function loop(i) {
// The loop check
if (i < len) { // The post iteration increment
return readFile(i).thenReturn(i + 1).then(loop);
}
}).then(function() {
console.log("done");
}).catch(function(e) {
console.log("error", e);
});
See it in jsfiddle http://jsfiddle.net/fd1wc1ra/
This is pretty much exactly equivalent to:
try {
for (var i = 0; i < len; ++i) {
readFile(i);
}
console.log("done");
} catch (e) {
console.log("error", e);
}
If you wanted to do nested loops it is exactly the same:
http://jsfiddle.net/fd1wc1ra/1/
function printItem(item) {
return new Promise(function(resolve) {
setTimeout(function() {
console.log("Item " + item);
resolve();
}, 500);
});
}
var mdArray = [[1,2], [3,4], [5,6]];
Promise.resolve(0).then(function loop(i) {
if (i < mdArray.length) {
var array = mdArray[i];
return Promise.resolve(0).then(function innerLoop(j) {
if (j < array.length) {
var item = array[j];
return printItem(item).thenReturn(j + 1).then(innerLoop);
}
}).thenReturn(i + 1).then(loop);
}
}).then(function() {
console.log("done");
}).catch(function(e) {
console.log("error", e);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…