Reputation: 4202
Can someone help me to understand 1 thing in this node.js code
let products = productModel.getAll().then(productIds => {
for (let i in productIds ) {
console.log("PROD_ID:"+productIds[i]);
alertModel.fetchAllByProductId(productIds[i]).then(alerts => {
console.log("Alerts for PROD_ID: " + productIds[i]);
console.log(alerts);
});
}
});
As you can see here i select all product ids then alerts for that products, as a result in console i have
PROD_ID: 1
PROD_ID: 10
PROD_ID: 18
Alerts for PROD_ID: 10
[...alerts data for 10 ]
Alerts for PROD_ID: 18
[...alerts data for 10 ]
Alerts for PROD_ID: 1
[...alerts data for 1 ]
As you can see first i have list of all product id cause alertModel.fetchAllByProductId is async method and until first alert select will have result system already finished loop over all product ids, but then once each alert data is selected in fetchAllByProductId.then i have correct productIds[i] for which that alert is selected, which is very strange ...
But by my understanding i should be already equal=3 and in all alert callbacks i should have always msg as Alerts for PROD_ID: 18 3 times ???
By my understanding i is lets say 1 variable which holds 1 memory slot in node.js env then how it is possible that in all 3 alert callbacks it has different value ???
So is there some place where i can read about this ? or can someone help and explain me this behave ?
Upvotes: 0
Views: 34
Reputation: 707416
But by my understanding i should be already equal=3 and in all alert callbacks i should have always msg as Alerts for PROD_ID: 18 3 times ???
let
creates a new i
for each invocation of the loop. So, while the loop is indeed done before any of your .then()
handlers get called, each iteration of the loop has it's own unique value of i
. This is a difference between let
and var
inside a for
loop. With var
, there is only one i
that all iterations of the loop refer to. let
and const
are different.
By my understanding i is lets say 1 variable which holds 1 memory slot in node.js env then how it is possible that in all 3 alert callbacks it has different value ???
let
and const
create a new and separate i
for each iteration of the for
loop so your .then()
handler gets to reference a copy of i
that belongs to it's specific iteration of the for
loop. This simplifies asynchronous code inside loops like this.
Here's a short article on the topic: https://wesbos.com/for-of-es6
Upvotes: 1