Asynchronous programming in Nodejs
Posted By : Ritik Jain | 15-Jan-2021
The Classical Approach - Callbacks
Let us explore these simple async operations. Here, the operation is to just start a timer, and at the end of the timer call a function.
function fastFunction (done) { setTimeout(function () { done() }, 100) } function slowFunction (done) { setTimeout(function () { done() }, 300) }
Also Read: How to Create Freshdesk Serverless App using Nodejs
Although we can execute the higher-order functions either sequentially or in parallel with the basic "pattern" by nesting callbacks, however, the method can result in an untameable callback-hell.
function runSequentially (callback) { fastFunction((err, data) => { if (err) return callback(err) console.log(data) // results of a slowFunction((err, data) => { if (err) return callback(err) console.log(data) // results of b // here you can continue running more tasks }) }) }
Also Read: Using a template engine in Nodejs
To handle this issue, we need to use the following approaches:-
Using Promises
function fastFunction () { return new Promise((resolve, reject) => { setTimeout(function () { console.log('Fast function done') resolve() }, 100) }) } function slowFunction () { return new Promise((resolve, reject) => { setTimeout(function () { console.log('Slow function done') resolve() }, 300) }) } function asyncRunner () { return Promise.all([slowFunction(), fastFunction()]) }
Using async and await
function scaryClown() { return new Promise(resolve => { setTimeout(() => { resolve('??'); }, 2000); }); } async function msg() { const msg = await scaryClown(); console.log('Message:', msg); } msg();
Thanks for reading.
Also Read: Using The Microservices and NodeJS
Turn To Our SaaS Application Development Services For A Great Return
We are a 360-degree software development company that provides complete web and mobile app development solutions for varied project requirements. Our end-to-end SaaS app development services address your mission-critical project requirements through scalable, responsive, and feature-rich software applications that are easy to scale. We carefully analyze your project requirements and formulate effective strategies to build enterprise-grade web and mobile applications for multiple platforms. For more info, contact us at [email protected].
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ritik Jain
Ritik is an accomplished Backend Developer with extensive experience in Mean. He is proficient in Core Java, Spring-Boot, Hibernate, Node.js, Angular 2+, and various relational databases like MySQL and MongoDB. With his expertise in API implementations, webservices, development testing, and deployments, he has contributed to the successful completion of various client projects. Apart from his professional pursuits, Ritik is an enthusiastic gamer and keeps himself updated with the latest advancements in technology.