To fix it , you should change var to let in for loop ( closure problem)
for(let a=0;a<3;a++)
The above result is because, var defines variable globally, or locally to an entire function regardless of block scope.
let allows you to declare variables that are limited in scope to the
block, statement, or expression on which it is used. This is unlike
the var keyword, which defines a variable globally, or locally to an
entire function regardless of block scope.
for example
for(var i = 1; i <= 5; i++) {
setTimeout(function() {
console.log('Value of i : ' + i);
},100);
}
The desired output of the above code is
Value of i : 1
Value of i : 2
Value of i : 3
Value of i : 4
Value of i : 5
But the actual output is
Value of i : 6
Value of i : 6
Value of i : 6
Value of i : 6
Value of i : 6
The above result is because, var defines variable globally, or locally to an entire function regardless of block scope.
for(let i = 1; i <= 5; i++) {
setTimeout(function(){
console.log('Value of i : ' + i);
},100);
}
Output:
Value of i : 1
Value of i : 2
Value of i : 3
Value of i : 4
Value of i : 5
in your case, your code will be:
for(let a=0;a<3;a++){
var test_promise = new Promise(function(resolve,reject){
setTimeout(()=>{
console.log("looping: " + a);
resolve('test' + a);
},3000);
});
overall.push(test_promise);
}