Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Beginners

    Automating and Scheduling Tasks Using Python

    Programming

    Node.js Experience

    JavaScript

    Node.js Lesson 13: Debugging in Node.js

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Node.js / Node.js Lessons / Node.js Lesson 14: Asynchronous Development
    JavaScript

    Node.js Lesson 14: Asynchronous Development

    Mohammad Shad MirzaBy Mohammad Shad MirzaJanuary 6, 2021Updated:January 6, 2021No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Node.js Lesson 14: Asynchronous Development
    Node.js Lessons 14: Async Development
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Node.js Lesson 14: Asynchronous Development
    Node.js Lesson 14: Asynchronous Development

    Hello everyone, we are going to learn about async development in this lesson. First, we will learn about what are async tasks and then learn how to handle them. Let’s start.

    What is Asynchronous Operation

    Asynchronous Operation refers to the flow of execution when something doesn’t follow the line by line execution of code but waits for some time. Set timeout is a general of an asynchronous task. What happens when you create a timeout task? JavaScript doesn’t wait for it to resolve, the whole flow of execution will be blocked if that happened. JavaScript continues to the next line and sends the timeout call-in event loop. Once the timeout is resolved, it runs that function. Here, two different are happening without blocking resources for the other one.

    Let’s look at another example: API requests. When you call an API, it doesn’t resolve instantly. It takes a little time for it to resolve and JavaScript can continue doing other tasks while the request is in progress. This asynchronous behavior of JavaScript is what makes it so powerful. Now one thing to note here is, the JavaScript won’t end the execution of code until the requests resolve either in success or failure. JavaScript will wait for it to resolve even if there is nothing to execute further, at least for a specific time of waiting. Let’s talk some more about this with the help of callbacks.

    Callbacks in JavaScript

    We can pass a function to any asynchronous function and call it when the request is complete. That passed will be called as callback in javascript. It means that I will call you back later. Let’s see how:

    setTimeout(() => {
        console.log('timeout');
    }, 1000);

    Here, the setTimeout function takes two arguments: a callback and a timeout interval. The function passed in the first arguments serves as a callback as it will only be called after the delay. We can use such usage of the callback function to handle asynchronous tasks. There are other ways of handling asynchronous tasks. Let’s look at promises.

    Promises in JavaScript

    JavaScript deals with asynchronous tasks with the help of promises. What is a promise?
    You can understand it as the literal meaning of the term promise. When we say we created a promise, we mean that this function promises us to return some data after some time. Promises will either resolve in success or failure but we can use it to add instructions about what happens when then promise results in success and failure. Let’s look at the code.

    const promise = new Promise(function(resolve, reject) {
      if(success){
          resolve();
      } else {
          reject();
      }
    });

    The above code is how you create a promise in JavaScript. It takes a function with two arguments: resolve and reject. We use resolve to end the promise if the request was successful and reject if the request has failed for some reason. Now how to use it?

    promise.then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log(error);
    });

    Promises can be chained with .then() call which will only be called if the promise was successfully resolved. Similarly, we can chain it with a .catch() call which will only be called the promise is failed. We can use these to handle success and failure.

    Read More:  5 Essential SEO Tips for Web Developers

    There is one other way to use promises and that is async/await syntax. It’s just a sugar coat over promises and makes it easy to use as well as provide more readability.

    async function (){
        try {
          const result = await promise();
          console.log(result);
        } catch (error) {
          console.log(error);
        }
    }

    The function must be marked with the async keyword to use await syntax inside it. Code marked with await syntax will stop the normal flow of javascript execution and wait for the promise to resolve instead. We wrap the call with a trycatch block to handle the case of failure. Let’s talk about the usage of promises in the Nodejs environment.

    Handling Promises in Nodejs

    In any real-life scenario, it hardly ever happens that we get a response immediately. That means dealing with a lot of asynchronous tasks in a production app. Let’s consider this example where we try to read file content:

    const http = require('http');
    const fs = require('fs');
    const port = 1337;
    const host = 'localhost';
     
    const server = http.createServer(function (req, res) {
        const data = fs.readFileSync('index.html');
        res.end(data);
    });
     
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    Here, we are calling readFileSync which reads the file synchronously without any delay. Imagine what will happen if the file is present in another location and it gets a little delay to read the file. This won’t work. We will have to use callback instead.

    const http = require('http');
    const fs = require('fs');
    const port = 1337;
    const host = 'localhost';
     
    const server = http.createServer(function (req, res) {
        fs.readFile('index.html', function(err, data) {
            if(err){
                return res.status(500).end();
            }
            res.end(data);
        });
    });
     
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    We changed the readFileSync method to readFile, it’s no longer a synchronous operation. We passed another function after the filename. This function will run after the read file operation is complete. This callback function receives two arguments: error and data. We can use these two to handle both success and failure cases.

    Read More:  Monthly Digest of the Most Popular and Trending JS GitHub Repos

    Usually using callbacks is not so great because you might stumble upon a problem called Callback Hell. Callback Hell is a situation where you keep adding callbacks to other callbacks to handle a series of asynchronous tasks. For this reason, it is preferred to use promises instead.

    Now the function readFile is a callback-based function and doesn’t support promises so you will have to convert it into a promise first. We can use our good old util module for this purpose. Let’s see how:

    const http = require('http');
    const fs = require('fs');
    const util = require('util');
    const port = 1337;
    const host = 'localhost';
     
    const server = http.createServer(function (req, res) {
        // convert readFile into a promise based method
        const readFilePromise = util.promisify(fs.readFile);
    
        // use promise instead
        readFilePromise('index.html').then(data => {
            res.end(data);
        }).catch(error => {
            res.status(500).end();
        })
    });
     
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    We used util. promisify() to convert fs.readFile into a promise and then used the .then chaining method over it. When you have to deal with multiple async tasks, you can keep adding .then one after another and avoid the callback hell problem.

    Now when we are using promises, we can also use async/await syntax to make our code a little more readable.

    const http = require('http');
    const fs = require('fs');
    const util = require('util');
    const port = 1337;
    const host = 'localhost';
     
    // add async to parent function
    const server = http.createServer(async function (req, res) {
        // convert readFile into a promise based method
        const readFilePromise = util.promisify(fs.readFile);
    
        try {
            // wait for promise to resolve
            const data = await readFilePromise('index.html');
            res.end(data);
        } catch (error) {
             res.status(500).end();
        }
    });
     
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    It looks much better and easy to read, don’t you agree? So today we learned what is an asynchronous operation. How to handle them using callbacks and promises. We also saw how to use async/await syntax. We learned why using callbacks is not the best option because of callback hell. We looked at a real-life example of how to read files asynchronously with callback, promise and async/await. That’s all for today. I hope this lesson was helpful to resolve all your doubts regarding asynchronous operation.

    You can find this lesson coding in our repository.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Streamlining Resource Allocation for Enhanced Project Success

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Angular March 2, 2020

    How to Create a Personal Blogging Website: Front-End (Angular) #2

    In this article, we are going to create the client-side part of the personal blogging website using Angular. 

    How to Stay Motivated While Working Remotely/Freelancing?

    February 8, 2020

    Libero Enim Sedfaucibus Turpis Magna Fermentum Justoeget

    January 28, 2020

    Fundamentals of Programming: A Beginner’s Guide

    November 25, 2024

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Effective Strategies to Secure Funding for Your Startup

    Startups November 24, 2024

    Effective Strategies to Overcome International Recruitment Challenges

    Recruitment December 6, 2024

    Essential Contributions of Backend Development in Full-Stack Projects

    Development December 6, 2024

    Инструменты JavaScript / Node.js разработчика

    Programming January 14, 2016

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Beginners

    Developer Guide to GDPR

    Startups

    Startup Spotlight: Five Companies That Revolutionize Healthcare & Wellness

    JavaScript

    Build Real-World React Native App #11 : Pay For Remove Ads

    Most Popular

    JavaScript Closures and Scoping: Understanding Execution Context and Variable Hoisting

    JavaScript

    Уроки React. Урок 6.

    Programming

    Enhancing Development Quality Through Effective Code Reviews

    Development
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.