我见过的任何带有promise循环的辅助函数实际上使它变得比您可以使用递归开箱即用的方法差很多。
是的,
.thenReturn但是更好一点:
function readFile(index) { return new Promise(function(resolve) { setTimeout(function() { console.log("Read file number " + (index +1)); resolve(); }, 500); });}// The loop initializationPromise.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);});在jsfiddle中查看http://jsfiddle.net/fd1wc1ra/
这几乎等同于:
try { for (var i = 0; i < len; ++i) { readFile(i); } console.log("done");} catch (e) { console.log("error", e);}如果要进行嵌套循环,则完全相同:
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);});


