I have seen different recommendation of coding format/styles in JavaScript. One of them is to omit , and ; at the end of each line unless the , is used in a JSON object. Another is to use only var to declare variables and indent 2nd variable onward.
I adopted both recommendation and this has caused me one interesting bug that I'd like to seek deeper understanding of the issue.
Initialization
var max = 2
arr = []
wait = 10
//Preset arr with simple object {id:i}
for(var i = 0; i < max; i++) arr.push({id:i})
Main Function
function simulate(idIn, callback) {
var msg = idIn
id = idIn
logger.info(idIn, 'simulate', JSON.stringify({id:id, idIn:idIn}))
setTimeout(function() {
var obj = {id:id, idIn:idIn}
logger.info(idIn, 'init', JSON.stringify(obj))
callback()
}, wait)
}
Paralleled Execution
async.map(arr, function(item, cb) {
logger.info('map', JSON.stringify(item))
simulate(item.id, cb)
}, function(err, result) {})
Output
info: map {"id":0}
info: 0 'simulate' '{"id":0,"idIn":0}'
info: map {"id":1}
info: 1 'simulate' '{"id":1,"idIn":1}'
info: 0 'init' '{"id":1,"idIn":0}' //id is overwritten here
info: 1 'init' '{"id":1,"idIn":1}'
As you can see from the output, the local variable id is overwritten with incoming value of idIn parameter during the wait. I fixed the issue by simply adding a , in the variable declaration of the simulate function.
var msg = idIn, //Added comma here.
id = idIn
I suppose this means , cannot be omitted in multiple variable declaration if you want to use only one var keyword. I'm trying to understand what happens to the 2nd variable id when , is omitted? Does this change its scope or it's made to something else?
,operator leads to automatic semicolon insertion (ASI):var msg = idIn; id = idIn;Now thevarkeyword is omitted. Since your variable declarations are in local scope,idgets a global variable.