I have multiple functions that are called back with data as it is received/parsed, and I need the data in one call back matched up to the data from another call back, which happen at different times.
For example, I have the following code to receive emails using pipedrive/inbox (github) client
and andres9/mailparser (github) mailparser
:
// List newest 10 messages
client.listMessages(-5, function(err, messages){
messages.forEach(function(message){
var mailparser = new MailParser();
// setup an event listener when the parsing finishes
mailparser.on("end", function(mail_object){
console.log("---------------------------------------------------------<<<");
console.log("Text body:", mail_object.text); // How are you today?
console.log(">>>---------------------------------------------------------");
});
console.log(message.UID + ": Subject: < " + message.title + "> Flags: <" + message.flags + ">");
client.createMessageStream(message.UID).pipe(mailparser);
//send the current email to the parser
});
});
The problem is that the console shows the message titles and flags all one after another, first, then shows all the parsed bodies one after another:
884: Subject: <[eBook] Executive's Guide to the Top 20 CSCs> Flags: <>
888: Subject: <Free Cloud-based Vulnerability Scanner> Flags: <\Seen>
896: Subject: <Unexpected sign-in attempt> Flags: <\Seen>
902: Subject: <[Watch] Backoff POS Malware: Key Indicators of Compromise> Flags: <$NotJunk>
918: Subject: <test subject 1> Flags: <$NotJunk>
[... Then here are all the bodies ...]
[... Message #884's body ...]
[... Message #888's body ...]
[... and so on ..]
When I want
884: Subject: <[eBook] Executive's Guide to the Top 20 CSCs> Flags: <>
[... Then message #884's body ...]
888: Subject: <Free Cloud-based Vulnerability Scanner> Flags: <\Seen>
[... Then message #888's body ...]
Eventually I will have this app send the full parsed messages (along with their parsed headers) to a database and also to the browser, and I need the flags and other metadata/headers paired with the parsed body when I do this, not logically separated by callbacks.
What is the best practice in Node.js for accomplishing this? What's the standard way to deal with separate callbacks for the same logical entities and are there different ways to deal with this?