Practical difference between async await and callback

In one of our tutorial, we learned how to create a function in async await and how to create a function that uses callback.

Video tutorial:

Asynchronous

Let’s say you want to send an email to a user. Following is a Node JS code that sends an email using a callback:

const transport = nodemailer.createTransport({
	host: "",
	port: 465,
	secure: true,
	auth: {
		user: "",
		pass: ""
	}
})

transport.sendMail({
	from: "support@adnan-tech.com",
	to: "",
	subject: "Test",
	text: "Hello",
	html: "Hello"
}, function (error, info) {
	console.log("Mail sent: " + (new Date()))
})

console.log("I am called: " + (new Date()))

In your terminal, you will see that the “I am called:” message will be displayed instantly. But the “Mail sent:” message will be shown after a few seconds, once the mail is sent. It means that all lines of your code are executed at once, irrespective of the fact that the sendMail function will take some. The code is executed without waiting for any function to complete. This is asynchronous programming.

Synchronous

This can be converted into a synchronous function. Following is the synchronous version of the above code:

// the function must be async if await is used inside it

app.get("/sendMail", async function (request, result) {

	// send an email using a callback
	const transport = nodemailer.createTransport({
		host: "",
		port: 465,
		secure: true,
		auth: {
			user: "",
			pass: ""
		}
	})

	const info = await transport.sendMail({
		from: "support@adnan-tech.com",
		to: "",
		subject: "Test",
		text: "Hello",
		html: "Hello"
	})

	console.log("Mail sent: " + (new Date()))

	console.log("I am called: " + (new Date()))

	result.send("")
})

If you run the code now, you will have to wait for the sendMail function to finish before you see your log messages. This is synchronous programming.

Now you have understood the difference, let’s discuss where you should use async await and where you should use a callback.

Where to use async await

You should use the async await pattern when the next line of your code is dependent on the previous lines. For example, “you have to insert the record in the database only if the mail is sent successfully”. In this case, you must use async await so that your code will wait for the mail to be sent successfully, then it will insert it in the database.

Where to use callback

A callback will be helpful when your code sections are independent of each other. For example, “send an email to the user and insert the record in the database.” In this case, your insertion query should not have to wait for the mail to be sent. The mail should be handled in a callback.

[wpdm_package id=’2034′]