100xDevs Full Stack Web Development Cohort Journey
Asynchrnous Nature of JS, Promises and async,await
100xDevs Full Stack Web Development Cohort Week 2.1
Learning about the foundation of JS and NodeJS was quite a good week. We are coming up with blogs for Mastering JS and NodeJS with Interview Questions to make it an end-to-end wrap for the learning.
The topics covered for this session are :
Asynchronous Nature of JS
Promises
await, async
Asynchronous Nature of JS
Assume you are working on a task, and immediately, you were appointed to some other task. You may switch to that complex task, but what if you assign this task to some other guy and notify you if the task is completed to make a call.
That is what JS does for complex tasks like reading a file and fetching the data for which the control halts for them to complete the reading or fetching, so they are used as asynchronous functions.
whenever the corresponding function fs.readFile() or fetch() is called, the function runs asynchronously (think of it like it was given to someone to operate and return the callback function to the main execution in the callback queue)
console.log('the start of the code')
setTimeout(()=>{console.log('the message after 5 seconds')},5000)
console.log('the end of the code')
what do you think the output for the above code would be? Probably, you might have a wrong answer if you didn't know about the asynchronous functions. This should be the output.
start of the code the code
the end of the code
the message after 5 seconds
When the control comes on to the setTimeout() after executing the first line of code, here it is an asynchronous function, so the controls skip it as it may take a longer time for execution and assign it to some other (we will learn about the execution of asynchronous function soon) unit and run the next line of code.
When the main control is free of all execution, it checks the callback queue, which consists of the callback functions from the asynchronous functions, and executes them. That's why, we have the output in that order
Promises
A Promise is a JavaScript object that represents an asynchronous operation's eventual completion or failure and its resulting value. It's a way to handle asynchronous code in a more organized and readable way.
Creation of the Promise
const NewPromise = new Promise((resolve, reject) => { const operationSuccess = true; if (operationSuccess) { resolve("Operation successfull"); } else { reject("Operation unsuccessful"); } });
Consuming the promise
NewPromise.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err);
});
Async & Await
async/await
is a feature in JavaScript that simplifies working with asynchronous code, making it look and behave more like synchronous code. It's built on top of promises and provides a cleaner syntax for handling asynchronous operations.// Asynchronous function that returns a promise function delay(ms) { return new Promise(resolve => { setTimeout(resolve, ms); }); } // Asynchronous function using async/await async function example() { console.log('Start'); // The 'await' keyword pauses execution until the promise is resolved await delay(2000); // Pause for 2 seconds console.log('After 2 seconds'); } // Call the async function example();
Execution of Asynchronous functions
CALL STACK
Definition: The call stack is a data structure that keeps track of the execution context (function calls) in a program.
How it Works:
When a function is called, a new frame is pushed onto the call stack.
When a function completes, its frame is popped from the stack.
JavaScript is single-threaded, and the call stack is where the execution of synchronous code takes place.
WEB APIs
Definition: Web APIs are browser-specific APIs that allow JavaScript to interact with the browser environment, such as making HTTP requests or setting timers.
How it Works:
When an asynchronous operation (e.g.,
setTimeout
, HTTP request) is encountered, it is offloaded to the browser's Web API environment.The Web API handles the asynchronous task and places it in the callback queue when it's done.
CALL BACK QUEUE
Definition: The callback queue is a queue that holds callbacks (functions) of completed asynchronous tasks.
How it Works:
When an asynchronous task completes (e.g., a timer expires, an HTTP request returns), its associated callback is placed in the callback queue.
The callback queue is FIFO (First In, First Out).
EVENT LOOP
Definition: The event loop is a mechanism that continually checks the call stack and callback queue for tasks.
How it Works:
The event loop constantly checks if the call stack is empty.
If the call stack is empty, it looks at the callback queue.
If there are callbacks in the queue, the event loop picks one and pushes its corresponding function onto the call stack.
The function is executed, and the process repeats.
Putting it All Together (Example):
Let's consider an example with a setTimeout:
javascriptCopy codeconsole.log('Start');
setTimeout(() => {
console.log('Timeout callback');
}, 2000);
console.log('End');
The
console.log('Start')
andconsole.log('End')
are pushed onto the call stack and executed synchronously.The
setTimeout
encounters an asynchronous operation. The timer is started, and thesetTimeout
function is offloaded to the Web API.The call stack is now empty, and the event loop checks the callback queue.
After 2 seconds, the timer expires, and the
setTimeout
callback is placed in the callback queue.The event loop sees the callback in the queue and pushes it onto the call stack.
The
console.log('Timeout callback')
is executed.
Please follow the journey, even if you are not a part of the cohort, following the curriculum and assignments can make you a better developer at the MERN stack.
Please find the codes, and assignments for the cohort in the GitHub Repository
Stay tuned for the upcoming blogs and exciting algorithms.