I have a situation similar to what you see below. The variable id is set to '03' before the first asynchronous callback is returned. Is there a way to deep copy, or "close" around the variable like you can with blocks in Objective-C? Is there a best practice?
var ids = ['01', '02', '03'];
for(var i=0, i < ids.length; i++){
var id = ids[i];
collection.find({id: ids} function () {
console.log(id);
});
}
The console output is:
03
03
03
There are several ways to do it. One is to iterate with a a method that uses a closure as a callback.
ids.forEach(function (elem) {
collection.find({id: ids} function () {
console.log(elem);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With