Node.js async tutorial – Mass Mailer example

Node.js is asynchronous in nature and runs on single threaded event loop. But how that work ? Well let’s say you have fired a database query and you are waiting for query to execute and then proceed further, but in a same scenario what will happen to the piece of code which are not dependent on that database query ? they won’t execute and wait for their turn.

Asynchronous is exactly opposite of this. While you are doing database query Node.js will continue executing code and when database query will be done, it will come back to process it.

This is one of the great feature to improve performance of the application but as a developer you got little more pain to handle particular scenarios ( like sending E-mail Mass mailer ) or your code will turn-up into callback hell.

Our demo application :

To demonstrate use of Async package i am going to show you how to build mass mailer program which can run as background job and pick up email from database, invoke email sending operation parallel and once done, gives you complete result.

For.eg : Let’s say i have 100 emails and i want to invoke email operation but other than sending an email what i need to do is to have a record of emails which are successfully sent and also which are failed so i need database update too.

What i can normally is write a Node.js function which returns me list of emails, invoke another function which send email to one of the email from the list, once it is done, another function to update database.

After updating database check whether list is empty or not and if not repeat same. Very well, simple and sweet.

But i am not gonna do that ! What i am gonna do is invoke email sending operation at once. That means if i got 100 emails, i should send email all of them at once because none of them is related with each other so there is no point to wait to send email to [email protected] after [email protected] is done.

Too much explanation. Let’s talk code !

About Async.

Async is node.js package and it is designed to control execution flow of asynchronous program like JavaScript. Async is available for Node.js as well as for browsers. In this tutorial i am going to use two function called .each and .waterfall function. There are many more in the documentation.

.each : This is like For loop in asynchronous nature, you can call modules using .each in parallel..waterfall : Modules written in waterfall will pass data to next module until last module is over.

/*
* This function will be called by multiple instance.
* Each instance will contain one email ID
* After successfull email operation, it will be pushed in failed or success array.
*/

massMailer.prototype.SendEmail=function(Email,callback){
console.log("Sending email to "+ Email);var self =this;
self.status=false;// waterfall will go one after another// So first email will be sent// Callback will jump us to next function// in that we will update DB// Once done that instance is done.// Once every instance is done final callback will be called.
async.waterfall([function(callback){var mailOptions ={
from:'[email protected]',
to: Email,
subject:'Hi ! This is from Async Script',
text:"Hello World !"};
transporter.sendMail(mailOptions,function(error, info){if(error){
console.log(error)
failure_email.push(Email);}else{
self.status=true;
success_email.push(Email);}
callback(null,self.status,Email);});},function(statusCode,Email,callback){
console.log("Will update DB here for "+ Email +"With "+ statusCode);
callback();}],function(){//When everything is done return back to caller.
callback();});}

new massMailer();//lets begin

Code is little bit tricky because there is so much callbacks but i am sure after looking to this diagram you will understand it better.async.each will take email list from an array and call sendMail() function “n” number of times at once. Inside sendMail() function i am executing email sending operation and updating database operation in waterfall way, i.e first send mail, get the result ( email send or not ) then update the database. Once all the parallel process is done. You will see the result in console.

Here is the output.

More about Async package:

Async is one of the great contribution to node.js community. With this package you can control the flow of execution of your program like never before. Whether its serial, parallel, waterfall or queuing, async won’t disappoint you.

Please visit their documentation once and don’t forget to star it on Github.

Conclusion:

I have lot to say about Async but at same time i don’t wanna increase the size of this tutorial. Next couple of weeks you will hear more about Async and its example usage in various real time scenarios. Meantime you can visit their documentation and learn more !

Asycn.parallel will execute those task in parallel while async.waterfall will call one after another by passing one function data to another and so on. Here my need was that, i want to send the mail and update DB but only after mail is sent. If i do it parallel both operation will execute on same time and this won’t solve my problem.

I don’t see error msg as case 1, but It just doesn’t go to next functions
function(statusCode,Email,callback) {..} and optional callback function.
and then
Dump: success_email, failure_email into aysnc.each();