We are working on a fun Node.js project at work. However, we were doing a for-loop with a callback and had big problems to pass in the variable into the callback-function. Either it was undefined or all entries had the same value.
We had this bit of code that wasn’t working:
for( var i = 0; i < formattedRoomList.length; i++ ){ var id = formattedRoomList[i].id; client.calendar.events.list({calendarId: formattedRoomList[i].id, timeMax: toDate, timeMin: fromDate }).withAuthClient(oauthClient).execute(function(err, result) { console.log(id); if (err) { console.log('getCalendars: An error occurred:', err); } else { var customId = { customId : id }; resultData.push(extend({},result,customId)); } callbackCounter++; if(callbackCounter == formattedRoomList.length) { callback(resultData); console.log(resultData); } }); }
To get it to work correctly we needed to wrap it with an anonymous function and pass it in. Just like this:
for( var i = 0; i < formattedRoomList.length; i++ ){ var id = formattedRoomList[i].id; client.calendar.events.list({calendarId: formattedRoomList[i].id, timeMax: toDate, timeMin: fromDate }).withAuthClient(oauthClient).execute( (function(id) { return function(err, result) { console.log(id); if (err) { console.log('getCalendars: An error occurred:', err); } else { var customId = { customId : id }; resultData.push(extend({},result,customId)); } callbackCounter++; if(callbackCounter == formattedRoomList.length) { callback(resultData); console.log(resultData); } }; })(id) ); }