Answer the question
In order to leave comments, you need to log in
Why should an iterator be passed to a closure in a loop?
Good afternoon!
It's not the first day I write in JS, but I still can't figure out what's wrong with for in JS. Let's say:
'use strict';
const arrOfItems = [
'a',
'b',
'c'
];
let arr = [];
let item;
for (let i = 0, len = 3; i < len; i++) {
item = arrOfItems[i];
arr.push(() => {
return Promise.resolve(item); // Все промисы вернут C
});
}
arr = arr.map(item => item());
Promise.all(arr)
.then((results) => {
console.log(results);
});
'use strict';
const arrOfItems = [
'a',
'b',
'c'
];
let arr = [];
let item;
for (let i = 0, len = 3; i < len; i++) {
((item) => {
item = arrOfItems[i];
arr.push(() => {
return Promise.resolve(item);
});
})(item);
}
arr = arr.map(item => item());
Promise.all(arr)
.then((results) => {
console.log(results);
});
'use strict';
const arrOfItems = [
'a',
'b',
'c'
];
let arr = [];
for (let i = 0, len = 3; i < len; i++) {
const item = arrOfItems[i];
arr.push(() => {
return Promise.resolve(item);
});
}
arr = arr.map(item => item());
Promise.all(arr)
.then((results) => {
console.log(results);
});
Answer the question
In order to leave comments, you need to log in
for-, if-, switch-blocks do not create a context.
arr.push(() => {
return Promise.resolve(item); // Все промисы вернут C
});
let item;
for (let i = 0, len = 3; i < len; i++) {
((item) => {
item = arrOfItems[i];
arr.push(() => {
return Promise.resolve(item);
});
})(item);
}
for (let i = 0, len = 3; i < len; i++) {
((idx) => { // это для наглядности, её тоже можно назвать i и тогда она "затенит" внешнюю i
let item = arrOfItems[idx];
arr.push(() => {
return Promise.resolve(item);
});
})(i);
}
In the first example, move the item declaration into a loop. Let and const have scope - block {}
for (let i = 0, len = 3; i < len; i++) {
let item = arrOfItems[i];
arr.push(() => {
return Promise.resolve(item);
});
}
for (let i = 0, len = 3; i < len; i++) {
arr.push(() => {
return Promise.resolve(arrOfItems[i]);
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question