I'm using the Gmail API to retrieve messages in a loop and do a req.write() for each message. There's a callback for each api invocation, but how do I know when the whole set is done so I can end the response? I tried the following but noticed that the callbacks are not executed in order of array index so I can't just do the line I commented out.
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
console.log('- %s', message.id);
(function(e){
var request = gmail.users.messages.get({
auth:auth,
id:message.id,
userId: 'me'
}, function(err, response) {
if(err) {
console.log('API returned an error: ' +err);
return;
}
res.write(JSON.stringify(response,null,'\t'));
console.log(e);
//if(e==messages.length-1) res.end();
}
);
})(i);
}