Sequential iteration using ES6 promises
<p>I was expecting that below node.js code will print output in following order</p>

<p></p>

<pre><code>1000
2000
3000
4000
"All tasks completed"
</code></pre>

<p>Instead it is prints in below mentioned order</p>

<p></p>

<pre><code>"All tasks completed"
1000
2000
3000
4000
</code></pre>

<p>The code</p>

<pre><code>'use strict';

var tasks = [1000, 2000, 3000, 4000];
var promise = Promise.resolve();


function test() {
  tasks.forEach(function(task) {
    promise = promise.then(function() {
      setTimeout(function() {
        console.log(task);
      }, task);
    });
  });
}

test();

promise.then(function() {
  console.log('All tasks completed');
});
</code></pre>

<p>What needs to be modified so that "All tasks completed" will be printed last.</p>

<ol>
<li>My example uses ES6 promises and not bluebird . </li>
<li>Also I am not asking a general question about promises , rather it is about a specific example.</li>
</ol>