I’m trying to us Async.js to process an array of items. Is there some cute way to get this to work properly? If you’re smarter than I, you’d except that because of the deferred execution, http://3 gets printed three times.
var a_servers = ['http://1', 'http://2', 'http://3'];
var a_actions = [];
for (var i = 0; i < a_servers.length; i += 1)
{
var server = a_servers[i];
a_actions.push(function(callback)
{
document.write(server + '<br/>');
callback(false, server );
});
}
async.series(a_actions, function(err, a_servers)
{
document.write('processed ' + a_servers.length + ' servers<br>');
console.info(a_servers);
});
You have a classic closure scope issue. You need to pass the
servervariable from the outer scope to the inner scope to get the desired behavior. You can use an IIFE for this.