I was expecting that below node.js code will print output in following order
1000
2000
3000
4000
"All tasks completed"
Instead it is prints in below mentioned order
"All tasks completed"
1000
2000
3000
4000
The 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');
});
What needs to be modified so that "All tasks completed" will be printed last.
- My example uses ES6 promises and not bluebird .
- Also I am not asking a general question about promises , rather it is about a specific example.