If all you are trying to do is 7 using promises, then this will do it:
function f(p, i) { return p.then(function() { return new Promise(function(r) { return setTimeout(r, 300); }); }) .then(function() { console.log(i); }); } var p = Promise.resolve(); for (var i = 0; i < 8; i++) { p = f(p, i); } p.then(function() { console.log('fin'); }) .catch(function(e) { console.log(e.message); });
The loop with promises is difficult because it is almost impossible not to fall into the JavaScript loop closure in the loop trap , but it is doable. The above works because it pushes all use of .then () into a subfunction f loop (i.e., Far from the loop).
The safer solution I'm using is to drop loops and look for patterns like forEach and reduce when possible, because they effectively force you to a subfunction:
[0,1,2,3,4,5,6,7].reduce(f, Promise.resolve()) .then(function() { console.log('fin'); }) .catch(function(e) { console.log(e.message); });
here f is the same function as above. Give it a try .
Update: In ES6, you can also use for (let i = 0; i < 8; i++) to avoid the “loop in loop” trap without inserting code into the f subfunction.
PS: The error in your example .then(main(), - it should be .then(function() { return new Promise(main()); }, , but in fact, I think that you are using it incorrectly template. main() should return a promise, not wrap it.