Quang Hoàng Quang Hoàng - 5 months ago 11
Javascript Question

JavaScript scope pitfall with Promise

I have an array B contains words like this

B = ['hello', 'love', 'peace']

I am trying to create a Promise array P:



for(var i = 0; i<B.length; i++){
var line = B[i];
var p = new Promise(function(resolve, reject){
setTimeout(function(){
resolve(line)},2000
);
})
P.push(p);
}

Promise.all(P).then(function(data){
console.log('data',data);
})





I expect array data will equal ['hello', 'love', 'peace'] but actually data = ['peace', 'peace', 'peace']

I read some posts about JavaScript scope pitfall but still can't figure out how to fix my code.

Please help me. Thanks in advance

Answer

if you use es6, you code may be like this

let B = ['hello', 'love', 'peace'];

let P = [];

for(var i = 0; i<B.length; i++){
 let line = B[i];
 let p = new Promise(function(resolve, reject){
   setTimeout(function(){
     resolve(line)
   },2000);
 })
 P.push(p);
}

Promise.all(P).then(function(data){
 console.log('data',data);
})

if you use the es5, you should var line = B[i]; in function p

Comments