Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it

7 Feb 2024

NODE JS - ASYNCHRONOUS PROGRAMMING


 1) What is Asynchronous Programming?



Asynchronous programming allows tasks to be executed concurrently without blocking the execution of other tasks and this can be achieved through callbacks, promises, and async/await.

Note that JavaScript is single-threaded. It carries out asynchronous operations via the callback queue and event loop.


2) Benefits of Asynchronous Programming?



1) Improved Performance - By avoiding blocking operations, asynchronous programming allows the application to continue executing other tasks while waiting for I/O operations to complete.
(Faster response times and better resource utilization).

2) Scalability - Asynchronous programming enables Node.Js applications to handle many concurrent requests without significant performance degradation.
(High-Performance web servers and real-time applications)

3) Responsive User Interfaces - Asynchronous programming ensures the user interface remains responsive even when performing time-consuming operations.
(Enhances the overall user experience and prevents applications from freezing)


3) Callbacks


Callbacks are a fundamental mechanism in Node Js for handling asynchronous operations.
Callbacks are functions passed as arguments to other functions and they are called once the operation is completed.

Example - 

const fs = require('fs'); 

fs.readFile('example.txt', 'utf8', (err, data) => { 
            if (err) { 
                        console.error(err); 
                        return; 
            
            console.log(data); 
});


4) Promises


Promises represent a value that may be available now, in the future, or never.
They allow chaining of asynchronous operations and handling of errors more elegantly.
Promises improve code readability and make error handling easier.

Example - 

const fs = require('fs').promises; 

fs.readFile('example.txt', 'utf8').
        then((data) => { 
        console.log(data); 
        }) 
        .catch((err) => { 
                console.error(err); 
        });

5) Async/ Await


Async functions enable writing asynchronous code in a synchronous-like manner using the 'async' and 'await'.
'async' - define an asynchronous function and 'await' - waits for promises to resolve.

Example - 

const fs = require('fs').promises; 

async function testingAsync() { 
        try { 
                const data = await fs.readFile('example.txt', 'utf8'); 
                console.log(data); 
        } catch (err) { 
                console.error(err); 
         

testingAsync();

No comments:

Post a Comment