I have a for-loop
which contains some local variables n
that is declared inside the loop. So I expected the value of n
to be destroyed once the program goes out of the loop.
However, it appears that the value of n
is still available outside of the for-loop. Why is that? Also, when should I expect the value of n (also the value k if uncommented)
to be destroyed?
const delayHelper = require('./delayExecutor')
async function main() {
let promises = [];
let records = [1, 2, 3, 4];
for(let i = 0; i < records.length; i++) {
let n = 1000 + records[i];
// let k = 123;
promises.push(delayHelper.delayResolve(() => records[i], 1000).then(data => data + n))
}
console.log(await Promise.all(promises)); //print: [ 1002, 1004, 1006, 1008 ]
}
main()
//delayExecutor.js
let delayedResolve = (fun, ms) => {
return new Promise((y, n) => {
setTimeout(() => {
y(fun());
}, ms);
});
};
exports.delayResolve = delayedResolve;