<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akshat on Medium]]></title>
        <description><![CDATA[Stories by Akshat on Medium]]></description>
        <link>https://medium.com/@akshatrastogi972?source=rss-8b963e84a688------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vvZ8ELrQEqJwkyjmmt9Alw.jpeg</url>
            <title>Stories by Akshat on Medium</title>
            <link>https://medium.com/@akshatrastogi972?source=rss-8b963e84a688------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 23 May 2026 16:03:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akshatrastogi972/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Today got a task to cover {load-balancer}]]></title>
            <link>https://medium.com/@akshatrastogi972/today-got-a-task-to-cover-load-balancer-a8011a688a0c?source=rss-8b963e84a688------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8011a688a0c</guid>
            <dc:creator><![CDATA[Akshat]]></dc:creator>
            <pubDate>Wed, 06 May 2026 20:47:46 GMT</pubDate>
            <atom:updated>2026-05-06T20:47:46.439Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Lets get into the basic defination of loadbalancer what are they supposed to do.</strong></p><p>A loadbalancer is a system that distributes incoming network traffic across multiple servers to ensure no single server get overwhelmed.</p><p>So,cool enough this is a bookish answer to the defination of load balancer.</p><p><strong>Now let me get to the core of the assignment i got..</strong></p><p><strong>You are required to redesign the load balancer logic. The task includes two provided code</strong></p><p><strong>components:</strong></p><p><strong>1. Code to generate random IP addresses.</strong></p><p><strong>2. Code to determine which node is hit.</strong></p><p>Cool now what is the actual deal here that as the number of nodes increases the client hitting the server is constantly hitting the wrong node which actualy create a good level of problem.</p><p>And this is something we are going to fix in this project or task</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNczUO3c9Ln8uK-0UlN77A.png" /></figure><p>This is the fix of the problem at a very beginner level.</p><blockquote><strong>So now lets start coding the solution</strong>.</blockquote><p>So first to do the maths around the ip address we need to find the hashed versions for ip address generated so that when we hit a simulate route we can check which ip is hiiting which</p><pre>// lets create a hash function to generate a hash value for the incoming ip adresses<br>function hashIP(ip){<br>    let hash = 0;<br>    for(let i = 0; i&lt;ip.length;i++){<br>        hash = (hash * 31 + ip.charCodeAt(i)) % 1000000007; <br>    }<br>    return hash;<br>}</pre><pre>hash = (hash * 31 + ip.charCodeAt(i)) % 1000000007;</pre><p>Reason behind using this formula is it keeps precision keeps the number small and prevent overflow and makes the distribution good.</p><blockquote><strong>NOW</strong></blockquote><p>The major logic of load balancer.</p><p>First we generate the hash value of ip and then find the modulus of that hashed ip with the no of nodes present in our system so that it can allot the unique node for the unique hashed ip which keeps the consistency same for the ip when used again later</p><pre>const nodes = [&quot;Node-A&quot;, &quot;Node-B&quot;, &quot;Node-C&quot;];<br>function identifyNode(ip, selectedNode) {<br>console.log(`Incoming IP: ${ip} → Routed to: ${selectedNode}`);<br>}<br>function LoadBalancer(ip) {<br>    const hashvalue = hashIP(ip);<br>    const nodeindex = hashvalue % nodes.length;<br>    const selectednode = nodes[nodeindex];<br>    identifyNode(ip, selectednode);<br>    return selectednode;<br>}</pre><blockquote>Used the function identifynode to log the ip and selected node in the terminal</blockquote><p>Now this is the major part of the solution now we can make routes over this functions to get the the data in json form when used a cli like postman.</p><pre>app.post(&quot;/route&quot;,(req,res)=&gt;{<br>    const {ip} = req.body;<br>    if(!ip){<br>        return res.status(400).json({<br>            msg:&quot;ip adress is not entered&quot;<br>        })<br>    }<br>    const result = LoadBalancer(ip);<br>    res.status(200).json({<br>        msg:&quot;request routed successfully&quot;,<br>        node:result<br>    })<br>})</pre><p>This works when you put a ip in json form in postman and check the route as a real client.</p><blockquote>The simulation route when we use generated random ip</blockquote><pre>app.get(&quot;/simulate&quot;,(req,res)=&gt;{<br>    const count = parseInt(req.query.count) || 10; // defaulted to 10 if not provided <br>    const results = []// made a in memory database to store the results of the simulation<br>    for(let i  = 0; i&lt;count; i++){<br>        const randomip = generateRandomIP();<br>        const node = LoadBalancer(randomip);<br>        results.push({<br>            ip:randomip,<br>            node:node<br>        })<br>    }<br>    res.status(200).json({<br>        msg:&quot;simulation completed&quot;,<br>        data:results<br>    })<br><br>})</pre><p>Ok i agree this can also be done by just writing a basic function which can be..</p><pre>function simulateTraffic(requestCount = 5) {<br>for (let i = 0; i &lt; requestCount; i++) {<br>const ip = generateRandomIP();<br>LoadBalancer(ip);<br>}<br>}<br>// Run simulation for 10 requests<br>simulateTraffic(10);</pre><p>this also works but i preferred writing a route on this.</p><p>Hence as you can see the problem is solved.</p><p>Now if today i hit my post route with one ip and again i hit it with same ip by twm or any other day it will always hit the same node as usual.</p><p>Will bring up the scalable solution also on the load-balancer blog but as of now this is the solution for fix nodes in the system.</p><p>Ok so i added bonus endpoint what if my node is down so lets add a healthcheckup endpoint</p><pre>// helath check for nodes<br>const nodestatus = {<br>    &quot;Node-A&quot;: true,<br>    &quot;Node-B&quot;: true,<br>    &quot;Node-C&quot;: true<br>}<br>function LoadBalancer(ip) {<br>    const hashvalue = hashIP(ip);<br>    const nodeindex = hashvalue % nodes.length;<br>    const selectednode = nodes[nodeindex];<br>    while(!nodestatus[selectednode]){<br>        nodeindex = (nodeindex+1)%nodes.length;<br>        selectednode = nodes[nodeindex];<br>    }<br>    identifyNode(ip, selectednode);<br>    return selectednode;<br>}</pre><pre>// health check endpoint for nodes<br>app.post(&quot;/health&quot;,(req,res)=&gt;{<br>    const {node,status} = req.body;<br>    if(!nodestatus.hasOwnProperty(node)){<br>        return res.status(400).json({<br>            msg:&quot;invalid node name&quot;<br>        })<br>    }<br>    nodestatus[node]= status;<br>    res.status(200).json({<br>        msg:&quot;node status updated successfully&quot;,<br>        node:node,<br>        status:status<br>    })<br>})</pre><p>Thanks for reading hope you loved it and you coded the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8011a688a0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TINDER BACKEND(proof of work)]]></title>
            <link>https://medium.com/@akshatrastogi972/tinder-backend-proof-of-work-98dac58645ae?source=rss-8b963e84a688------2</link>
            <guid isPermaLink="false">https://medium.com/p/98dac58645ae</guid>
            <dc:creator><![CDATA[Akshat]]></dc:creator>
            <pubDate>Fri, 01 May 2026 19:46:19 GMT</pubDate>
            <atom:updated>2026-05-01T19:46:19.350Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Built a Dating App Backend to Understand How Tinder Actually Works</h3><p><em>Not for production. Not for users. Just to answer one nagging question — what actually happens behind the scenes when two people swipe right at the same time?</em></p><p>Every time I used Tinder, it felt instant.</p><p>You swipe right… and somehow the system <em>knows</em> when it’s a match. No delay. No visible complexity. Just a clean <strong>“It’s a Match!”</strong> moment.</p><p>And that curiosity stayed in my head.</p><p>Surface-level answers weren’t enough. “They use databases” and “they use APIs” don’t explain anything meaningful. I needed to understand: how does the data flow? Where does it live? How does the system avoid showing you the same profiles twice?</p><p>So I built a simplified version myself — not to ship it, but as a <strong>proof of work</strong> to understand the system at a deep level.</p><p>The full source is on GitHub: <a href="https://github.com/requiremen/Tinder-backend-core">requiremen/Tinder-backend-core</a></p><p>Here’s how every part of it works.</p><h3>The Tech Stack</h3><ul><li><strong>Node.js</strong> — runtime</li><li><strong>Express.js</strong> — HTTP server and routing</li><li><strong>MongoDB + Mongoose</strong> — database and schemas</li><li><strong>JWT</strong> — authentication tokens</li><li><strong>bcrypt</strong> — password hashing</li></ul><h3>Step 1 — Foundation: app.js &amp; Server Setup</h3><p>Every real system starts somewhere modest. The entry point is src/app.js — it wires together Express, MongoDB, and all route groups:</p><pre>// src/app.js<br>const express = require(&#39;express&#39;);<br>const mongoose = require(&#39;mongoose&#39;);<br>require(&#39;dotenv&#39;).config();</pre><pre>const authRoutes  = require(&#39;./routes/authRoutes&#39;);<br>const userRoutes  = require(&#39;./routes/userRoutes&#39;);<br>const swipeRoutes = require(&#39;./routes/swipeRoutes&#39;);</pre><pre>const app = express();<br>app.use(express.json());</pre><pre>app.use(&#39;/api/auth&#39;, authRoutes);<br>app.use(&#39;/&#39;, userRoutes);<br>app.use(&#39;/&#39;, swipeRoutes);</pre><pre>mongoose.connect(process.env.MONGO_URI)<br>  .then(() =&gt; app.listen(3000, () =&gt;<br>    console.log(&#39;Server running on <a href="http://localhost:3000&#39;)">http://localhost:3000&#39;)</a><br>  ));</pre><p>No magic here — just a clean separation of concerns from day one. Each route group lives in its own file. The app file is responsible for nothing except assembly.</p><h3>Step 2 — Data Models: User, Swipe, Match</h3><p>The three Mongoose models define the entire shape of the system. Understanding these models <em>is</em> understanding the app.</p><h3>userModel.js</h3><pre>// src/models/userModel.js<br>const mongoose = require(&#39;mongoose&#39;);</pre><pre>const userSchema = new mongoose.Schema({<br>  name:     { type: String, required: true },<br>  email:    { type: String, required: true, unique: true },<br>  password: { type: String, required: true }, // bcrypt hash — never plain text<br>  age:      { type: Number },<br>  bio:      { type: String },<br>}, { timestamps: true });</pre><pre>module.exports = mongoose.model(&#39;User&#39;, userSchema);</pre><h3>swipeModel.js</h3><pre>// src/models/swipeModel.js<br>const mongoose = require(&#39;mongoose&#39;);</pre><pre>const swipeSchema = new mongoose.Schema({<br>  from:      { type: mongoose.Schema.Types.ObjectId, ref: &#39;User&#39;, required: true },<br>  to:        { type: mongoose.Schema.Types.ObjectId, ref: &#39;User&#39;, required: true },<br>  direction: { type: String, enum: [&#39;like&#39;, &#39;pass&#39;], required: true },<br>}, { timestamps: true });</pre><pre>module.exports = mongoose.model(&#39;Swipe&#39;, swipeSchema);</pre><blockquote><strong><em>Key insight:</em></strong><em> A swipe isn’t an animation — it’s just data. Two ObjectIDs and a direction string. That’s the entire abstraction.</em></blockquote><h3>matchModel.js</h3><pre>// src/models/matchModel.js<br>const mongoose = require(&#39;mongoose&#39;);</pre><pre>const matchSchema = new mongoose.Schema({<br>  users: [{ type: mongoose.Schema.Types.ObjectId, ref: &#39;User&#39; }],<br>}, { timestamps: true });</pre><pre>module.exports = mongoose.model(&#39;Match&#39;, matchSchema);</pre><p>The match model is intentionally minimal — just an array of two user IDs. The $all operator later uses this shape to prevent duplicate matches efficiently.</p><h3>Step 3 — Authentication &amp; JWT Middleware</h3><p>Before the system can know <em>who liked whom</em>, it needs to know who’s making each request. The auth service handles signup and login, and a middleware guards every protected route.</p><h3>authService.js</h3><pre>// src/services/authService.js<br>const bcrypt = require(&#39;bcrypt&#39;);<br>const jwt    = require(&#39;jsonwebtoken&#39;);<br>const User   = require(&#39;../models/userModel&#39;);</pre><pre>const signup = async ({ name, email, password }) =&gt; {<br>  const hashed = await bcrypt.hash(password, 10);<br>  const user   = await User.create({ name, email, password: hashed });<br>  return user;<br>};</pre><pre>const login = async ({ email, password }) =&gt; {<br>  const user  = await User.findOne({ email });<br>  if (!user)  throw new Error(&#39;User not found&#39;);</pre><pre>  const valid = await bcrypt.compare(password, user.password);<br>  if (!valid) throw new Error(&#39;Invalid credentials&#39;);</pre><pre>  const token = jwt.sign(<br>    { userId: user._id },<br>    process.env.JWT_SECRET,<br>    { expiresIn: &#39;7d&#39; }<br>  );<br>  return { token, user };<br>};</pre><pre>module.exports = { signup, login };</pre><blockquote><strong><em>Important:</em></strong><em> Passwords are never stored in plain text. </em><em>bcrypt.hash() with a salt round of 10 ensures that even if your database leaks, user passwords remain unreadable.</em></blockquote><h3>authMiddleware.js</h3><pre>// src/middleware/authMiddleware.js<br>const jwt  = require(&#39;jsonwebtoken&#39;);<br>const User = require(&#39;../models/userModel&#39;);</pre><pre>const protect = async (req, res, next) =&gt; {<br>  const authHeader = req.headers.authorization;<br>  if (!authHeader?.startsWith(&#39;Bearer &#39;))<br>    return res.status(401).json({ error: &#39;No token provided&#39; });</pre><pre>  const token = authHeader.split(&#39; &#39;)[1];<br>  try {<br>    const decoded = jwt.verify(token, process.env.JWT_SECRET);<br>    req.user = await User.findById(decoded.userId).select(&#39;-password&#39;);<br>    next();<br>  } catch {<br>    res.status(401).json({ error: &#39;Invalid or expired token&#39; });<br>  }<br>};</pre><pre>module.exports = { protect };</pre><p>The middleware attaches the full user object (minus the password) to req.user. Every downstream controller can then access the logged-in user without an extra database call.</p><h3>Step 4 — The Swipe System</h3><p>The swipe service is the heart of user interaction. It handles three things: preventing self-swipes, preventing duplicate swipes, and storing the result.</p><h3>swipeService.js</h3><pre>// src/services/swipeService.js<br>const Swipe = require(&#39;../models/swipeModel&#39;);<br>const Match = require(&#39;../models/matchModel&#39;);</pre><pre>const handleSwipe = async (fromId, toId, direction) =&gt; {<br>  // Guard: can&#39;t swipe on yourself<br>  if (fromId.toString() === toId.toString())<br>    throw new Error(&#39;Cannot swipe on yourself&#39;);</pre><pre>  // Guard: already swiped this person<br>  const existing = await Swipe.findOne({ from: fromId, to: toId });<br>  if (existing) throw new Error(&#39;Already swiped on this user&#39;);</pre><pre>  // Store the swipe<br>  await Swipe.create({ from: fromId, to: toId, direction });</pre><pre>  // Only check for a match on &#39;like&#39;<br>  if (direction === &#39;like&#39;) {<br>    const reverseSwipe = await Swipe.findOne({<br>      from: toId,<br>      to:   fromId,<br>      direction: &#39;like&#39;,<br>    });</pre><pre>    if (reverseSwipe) {<br>      // Prevent duplicate match documents using $all<br>      const matchExists = await Match.findOne({<br>        users: { $all: [fromId, toId] }<br>      });</pre><pre>      if (!matchExists) {<br>        await Match.create({ users: [fromId, toId] });<br>        return { match: true, message: &quot;It&#39;s a match! 💘&quot; };<br>      }<br>    }<br>  }</pre><pre>  return { match: false };<br>};</pre><pre>module.exports = { handleSwipe };</pre><p>The $all operator on the match check is the key to deduplication. It finds documents where the users array contains both IDs <em>in any order</em> — so [A, B] and [B, A] are treated as the same match.</p><h3>Step 5 — Match Logic: The Core Insight</h3><p>This was the part I was most curious about when I started, and the answer turned out to be a single database lookup.</p><p><strong>A match is just:</strong></p><pre>User A likes User B<br>AND<br>User B likes User A</pre><p>When User A swipes right on User B, the backend immediately asks: <em>“Did B already like A?”</em> If yes — create a match. If no — store A’s swipe and wait.</p><p>The match endpoint then fetches all matches for a user, populating both user documents while deliberately stripping passwords:</p><pre>// src/services/userService.js<br>const getMatches = async (userId) =&gt; {<br>  const matches = await Match.find({<br>    users: userId<br>  }).populate(&#39;users&#39;, &#39;-password&#39;);</pre><pre>  return matches;<br>};</pre><p>Calling .populate(&#39;users&#39;, &#39;-password&#39;) replaces ObjectID references with real user objects. The &#39;-password&#39; projection ensures sensitive data never leaves the server.</p><p>When I saw that first <strong>“It’s a match!”</strong> response from my own backend — even just in a terminal window — it genuinely felt exciting. Understanding <em>why</em> it works makes the moment hit differently.</p><h3>Step 6 — The Discover Feed</h3><p>The feed needs to feel endless and fresh — but must never surface a profile the current user has already swiped on. Here’s how the feed service builds that filtered list:</p><pre>// src/services/userService.js<br>const getFeed = async (userId) =&gt; {<br>  // 1. Find everyone the current user has already swiped<br>  const mySwipes = await Swipe.find({ from: userId });<br>  const seenIds  = mySwipes.map(s =&gt; s.to);</pre><pre>  // 2. Exclude self + already-seen profiles<br>  const excludeIds = [...seenIds, userId];</pre><pre>  // 3. Return only unseen users<br>  const feed = await User.find({<br>    _id: { $nin: excludeIds }<br>  }).select(&#39;-password&#39;).limit(20);</pre><pre>  return feed;<br>};</pre><p>The $nin (not in) operator does all the heavy lifting. What remains after filtering is a clean list of profiles the user has never seen — that&#39;s the entire illusion of infinite, fresh discovery.</p><blockquote><em>In production systems like Tinder, this query is augmented with geolocation, preference filters, and a ranking model. But the core exclusion logic is exactly this pattern.</em></blockquote><h3>Step 7 — Refactoring Into Real Architecture</h3><p>At this point the system worked — but everything was in a few large files. Refactoring into a layered architecture is where the real engineering lesson happened.</p><pre>src/<br> ├── models/       userModel.js · swipeModel.js · matchModel.js<br> ├── controllers/  authController.js · swipeController.js · userController.js<br> ├── services/     authService.js · swipeService.js · userService.js<br> ├── routes/       authRoutes.js · swipeRoutes.js · userRoutes.js<br> ├── middleware/   authMiddleware.js<br> └── app.js</pre><p>Each layer has one job and only calls the layer below it:</p><ul><li><strong>routes/</strong> — defines URL and HTTP method</li><li><strong>controllers/</strong> — handles request/response cycle</li><li><strong>services/</strong> — contains business logic</li><li><strong>models/</strong> — defines data shape</li><li><strong>middleware/</strong> — auth guard</li></ul><p>Here’s what that looks like in practice:</p><pre>// src/routes/swipeRoutes.js<br>const express  = require(&#39;express&#39;);<br>const router   = express.Router();<br>const { swipe } = require(&#39;../controllers/swipeController&#39;);<br>const { protect } = require(&#39;../middleware/authMiddleware&#39;);</pre><pre>router.post(&#39;/swipe&#39;, protect, swipe);</pre><pre>module.exports = router;</pre><pre>// src/controllers/swipeController.js<br>const { handleSwipe } = require(&#39;../services/swipeService&#39;);</pre><pre>const swipe = async (req, res) =&gt; {<br>  try {<br>    const { toId, direction } = req.body;<br>    const result = await handleSwipe(req.user._id, toId, direction);<br>    res.json(result);<br>  } catch (err) {<br>    res.status(400).json({ error: err.message });<br>  }<br>};</pre><pre>module.exports = { swipe };</pre><p>The controller knows nothing about database queries. The service knows nothing about HTTP. <strong>This separation means you can swap MongoDB for Postgres, or replace JWT with OAuth, without touching your business logic.</strong> That’s the real value of clean architecture — it isn’t just about tidiness, it’s about change tolerance.</p><h3>Step 8 — The Full System in One View</h3><pre>User logs in<br>    ↓<br>Gets JWT token → sent with every request<br>    ↓<br>Middleware verifies identity → attaches user to req<br>    ↓<br>GET /feed → excludes seen profiles via $nin<br>    ↓<br>POST /swipe → stores interaction in DB<br>    ↓<br>Check reverse swipe → did they already like me?<br>    ↓<br>Mutual like → Match.create({ users: [A, B] }) ❤️<br>    ↓<br>GET /matches → populate + return both users</pre><h3>API Endpoints</h3><p>Method Route Description POST /api/auth/signup Register new user POST /api/auth/login Login, receive JWT GET /me Get own profile PUT /me Update bio, age, etc. POST /swipe Like or pass a user GET /matches All mutual matches GET /feed Unseen users to swipe</p><p>All routes except signup and login require Authorization: Bearer &lt;token&gt; in the request header.</p><h3>What This Project Taught Me</h3><p>This wasn’t just about cloning an app. It taught me:</p><p><strong>Backend is about data relationships, not just APIs.</strong> The interesting question is never “how do I write a route” — it’s “how does data connect to itself.”</p><p><strong>Simple logic powers complex systems.</strong> The match detection is 5 lines. The feed filter is 4 lines. The complexity you <em>feel</em> as a user is mostly UI — the backend logic is remarkably compact.</p><p><strong>Database queries are the real brain.</strong> $nin and $all aren&#39;t just operators. They&#39;re the feed and the match system. The query <em>is</em> the feature.</p><p><strong>Structure matters as much as functionality.</strong> Writing code that works and writing code that scales are two completely different skills. Both take deliberate practice.</p><p>Most importantly — I stopped memorizing syntax and started understanding systems. That’s a completely different mode of learning, and a far more durable one.</p><h3>What’s Next for This Project</h3><ul><li>💬 Real-time chat with Socket.io</li><li>📍 Location-based matching</li><li>🎯 Filters for age, gender, and preferences</li><li>🔔 Push notifications</li><li>📱 React Native frontend</li></ul><h3>Check Out the Code</h3><p>The full source is available on GitHub: 👉 <a href="https://github.com/requiremen/Tinder-backend-core"><strong>requiremen/Tinder-backend-core</strong></a></p><p>If this helped you understand how backend systems actually work — give it a star. And if you have questions about any part of the implementation, drop them in the comments.</p><p><em>Curiosity built this. Not tutorials. Not copying. Just one question — “how does this actually work?” — followed all the way down to the database query.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98dac58645ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Promise you…..]]></title>
            <link>https://medium.com/@akshatrastogi972/i-promise-you-56c6452d86c7?source=rss-8b963e84a688------2</link>
            <guid isPermaLink="false">https://medium.com/p/56c6452d86c7</guid>
            <category><![CDATA[jobs-for-freshers]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Akshat]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 07:08:29 GMT</pubDate>
            <atom:updated>2026-02-18T07:08:29.162Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>well promise is a great class to know in javascript and yes is sugur coated way of writing a callback but yes its crazy how promise class conatins some functions which actualy makes the code readable and edible.</strong></p><pre>console.log(&quot;1 script runs&quot;)<br>setTimeout(function(){<br>    console.log((&quot;2 setTimeout runs,macrotask&quot;))<br>},0)<br>Promise.resolve().then(function(){<br>    console.log(&quot;3 promise runs,microtask&quot;)<br>})<br>console.log(&quot;4 script ends&quot;)</pre><p>look at this and think over what the output could be….</p><pre>1 script runs<br>4 script ends<br>3 promise runs,microtask<br>2 setTimeout runs,macrotask</pre><blockquote>this is something shows that both of the async task we are performing but the micro-task is running fast and where the core macro-task which is itself a async function is running last.</blockquote><p>So basically now let me think over this and show you also lol…</p><p>Now what i think the promise.resolve() looks like that it resolves very fast like having a empty function which have a new promise which only returns promise.resolve() lets check with that code as well</p><pre>console.log(&quot;1 script runs&quot;)<br>setTimeout(function(){<br>    console.log((&quot;2 setTimeout runs&quot;))<br>},0)<br><br>function emptyPromise(){<br>    return new Promise(function(resolve,reject){<br>        resolve()<br>    })<br>}<br><br>Promise.resolve().then(emptyPromise).then(function(){<br>    console.log(&quot;3 promise runs&quot;)<br>})<br>console.log(&quot;4 script ends&quot;)</pre><p>okay now this empty promise function is resolving directly and taking the lowest time as compared to the the timeout task. So yes i might be wrong at this i need review of you guys but lets look forward for some more cool things</p><p>Callback hell..</p><p>So how does callback hell looks like</p><pre>// lets have discussing aboout callback hell<br>setTimeout(function(){<br>    console.log(&quot;hi there&quot;)<br>    setTimeout(function(){<br>        console.log(&quot;welcome to callback hell&quot;)<br>        setTimeout(function(){<br>            console.log(&quot;lets get started&quot;)<br>        },3000)<br>    },2000)<br>},1000)</pre><p>this is how it looks like very clichee way to look at too many timeouts,so this is the reason coders prefer yousing promises to get out of it but hey let me also show you that, for that first lets write out our promisified version of setTimeout()</p><pre>function settimoutpromise(ms){<br>    return new Promise(function(resolve,reject){<br>        if(ms&lt;0){<br>            reject(&quot;invalid time&quot;)<br>        }else{<br>        setTimeout(resolve,ms)<br>        }<br>    })<br>}</pre><p>okay so this the promisified version of the settimout using the promise class itself now the lemme show how the call back hell will look in this as well lol..</p><pre>settimoutpromise(1000).then(function(){<br>    console.log(&quot;hi there&quot;)<br>    settimoutpromise(2000).then(function(){<br>        console.log(&quot;welcome to callback hell&quot;)<br>        settimoutpromise(3000).then(function(){<br>            console.log(&quot;lets get started&quot;)<br>        })<br>    })<br><br>})</pre><p>lol this seem to look like a promise hell but yes it can be chained in a proper manner lemme show you that now..</p><pre>settimoutpromise(1000)<br>.then(function(){<br>    console.log(&quot;hi there&quot;)<br>    return settimoutpromise(2000)      <br>}).then(function(){<br>    console.log(&quot;welcome to callback hell&quot;)<br>    return settimoutpromise(3000)<br>}).then(function(){<br>    console.log(&quot;lets get started&quot;)<br>}).catch(function(err){<br>    console.log(err)<br>})</pre><p>now this is how it looks in a chain format</p><p>So ultimately promise is better than callback hell its just because it is more readable syntax and easy to digest thats solve.. cool</p><p>Ok so promise is an object of an promise class which called to perform various asynchronous task and as of now we have seen timeout read and stuffs but in real life it is all about <strong>Database calls and Network calls.</strong></p><p>So lets get into the promise now we will get into writing promises</p><p>Okay so promise have 3 states</p><p>Pending,Fulfilled,Rejected — — -&gt; these are the 3 states of promise</p><pre>// writing the promisfied version of the fs.readFile function<br>// writing the promisified version of setTimeout function<br>// writing the promisified version of fs.writeFile function<br>// okay first letscatchup with the basic<br>function readfilepromise(filename,encoding){<br>    return new Promise();<br>}<br>// okay this is an empty promise <br>//lets look at how the hell it is called <br>const p  = readfilepromise(&quot;a.txt&quot;,&quot;utf-8&quot;).then(function(data){<br>    console.log(data);<br>    <br>}).catch(function(err){<br>    console.log(err);<br>    <br>})<br><br><br>// . then method is conatining the callback function which is called when the promise is resolved <br>// and the catch method is called when the promise is rejected</pre><p>look at the comments of the codebase it will get clear with time</p><pre>const p  = readfilepromise(&quot;a.txt&quot;,&quot;utf-8&quot;).then(function(data){<br>    console.log(data);<br>    <br>}).catch(function(err){<br>    console.log(err);<br>    <br>})</pre><p>for once consider promise function as a black box and marinate the stuff of calling a promise function</p><p>Okay so now understand this the promise class wants a function inside it which is its object maybe called new Promise like new Rectangle in the previous blog so its the responsibility of the class to run that function</p><p>So lets say that the promise class is written in such way that it requires function as an input</p><pre>return new Promise(function(){})</pre><p>got it…</p><p>so now a promise is written on the already made asynchronous call back function for here the example is fs.readFile ok so lets write it</p><pre>function readfilepromise(filename,encoding){<br>    return new Promise(function(resolve,reject){<br>        fs.readFile(filename,encoding,function(err,data){<br>            if(err){<br>                reject(err);<br>            }else{<br>                resolve(data);<br>            }<br>        })<br>    })<br>}</pre><p>So here the promisified version of the readfile is made in which the promise is taking a function as argument and then it contains 2 arguments resolve or reject which bascially written to use .then and .catch so that whenever any one of them is call the resolve or the reject argument of the promise class is called which we have given in the arguments of the function inside the new promise(fn).</p><p>So now i think you guys can imagine how the promise class may look like</p><pre>class promise(){<br>constructor(fn)<br>}<br>rsolve()<br>reject()</pre><p>all in all it might look like this and hence with clarity we have made a promisified version of readfile.</p><p>Okay i got very great insight as well would love to share as well setInterval this thing resolves multiple times and its not the best practise to write a promisified way of setinterval its just only written for a function which only resolves one time max. cool info tho..</p><p>Okay so lets put this into testing too will the promise resolve multiple times</p><pre>let p = new Promise(function(resolve, reject){<br>    resolve(&quot;helllo world&quot;);<br>    resolve(&quot;hello world again&quot;);<br>    resolve(&quot;hello world again and again&quot;);<br>})<br>p.then(function(data){<br>    console.log(data);<br>})</pre><p>the output be only hello world which actually proves that it resolves just one time.</p><p>thats it for today ……..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56c6452d86c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript]]></title>
            <link>https://medium.com/@akshatrastogi972/javascript-4d784c9e4c86?source=rss-8b963e84a688------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d784c9e4c86</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[freshers]]></category>
            <dc:creator><![CDATA[Akshat]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 20:14:45 GMT</pubDate>
            <atom:updated>2026-02-14T20:14:45.368Z</atom:updated>
            <content:encoded><![CDATA[<p>Well i was asked some questions related to javascript during an interview of Ola and was not able to answer that so i am writing this to help anyone who is going or lets say searching for an intern well i didn’t find one yet lol.</p><p>Event loop is something is which is constantly looking up at the call stack whether is there any callbacks in the callback queue it will push the first callback from the callback queue into the call stack for execution.</p><p>Callback queue — — → contains callback list who are waiting for the execution once the call stack is empty and hence,These tasks are added to the queue by Web APIs after they have completed their operation.</p><p>Web APIs are provided by the browser (or the Node.js runtime) and allow you to perform tasks that are outside the scope of the JavaScript language itself, such as making network requests, setting timers, or handling DOM events.</p><p>synchronous and asynchronous nature of javascript is the best part of it which makes the thing very easy for building web apps</p><p>In a layman terms async nature of javascript can be considered as deligate the task to someone you continuing with other task and conming back to it once the callback is called lol. I really hope you understand this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZFx9hjw9cvupnAFf1DeYw.png" /></figure><p>classes is the coolest stuff i have seen in javascript it just lets you add functions and properties to any variable you have created according to the class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8A-tLD08JbhdHGp97OO_pg.png" /></figure><p>here we can see that according to the class we implemented the feature into the variable this the magic of classes.</p><p>Other than that javascript provides its own class such as the date class</p><p>const d = new date() — — → syntax of using classes (this is class provided by javascript itself)</p><p>so this class now exposes a bunch of functions with you</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date</a> consider this to know about the functions being exposed by the date class for you</p><p>static methods</p><p>class rectangle {</p><p>constructor(width,height,color){</p><p>this.width = width;</p><p>this.height = height;</p><p>this.color = color;</p><p>}</p><p>static who(){</p><p>return “this is a rectamgle”</p><p>}</p><p>area(){</p><p>return this.width* this.height;</p><p>}</p><p>}</p><p>// static method is somethinng that is called on the class itself not required to called on an a object</p><p>let rect1 = new rectangle(10,20,”red”);;</p><p>console.log(rect1.who())// this will give an error because who is a static method and we are trying to call it on an object</p><p>console.log(rectangle.who())// this will work because we are calling the static method on the class itself</p><p>console.log(rect1.area())// this will work because area is not a static method and we are calling it on an object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z295FeqagDMOLdG962WPnQ.png" /></figure><p>this is for better under-satanding</p><p>Inheritance in js allows you to inherit common properties from all the classes into another parent class which enables the childeren to call out the parent class for it to take the input for example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5EeHnFHt7s8JJTquVWtUg.png" /><figcaption>common function paint is used in all the three classes</figcaption></figure><p>Now we can define a commom shape class which will be considerd as parent class and then henceforth called out</p><p>the syntax for it could be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLxYBW1NHd64ZjKajygveA.png" /></figure><p>The shape class is now the parent class and now we can call color easily in the children class.</p><p>Now the given the code here in the ss shows a major problem of hoisting now whats hoisting — → hoisting in javascript is something related to delceleration of a function before calling it assume you are making a call without phone but the function of phone of phone should be defined first to use that phone to make a call, hence over here the shape function should be called first before extending any children class to parent class, ooh cool i have one more example of it it can be having childeren without parents lol. but yeah this is basic hoisting in js.</p><p>Now let me start with some difficult bits according to me about the promise class so basically promise is also a class used to perform some async task lets say reading a file setting a timeout….etc</p><p>So as of now we know that setTimeout is a async task and it can be called using a callback function this was how the things were being managed back in 2014 but from 2015 some good genius folks wrote the promise class which may have the then() function inside it catch() function inside it and what not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juWRFO0hDP4WXWUWftG-Jw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACPqc_IohzNGz33dW9ubXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhIceGYhqdWd5Z_7ZJI1fg.png" /></figure><p>So now the major bit of writing a promisified version of a readfile</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0Q018LHTlacmtgFR8fmSw.png" /><figcaption>CRAZY STUFF</figcaption></figure><p>now this looks big but yes this is syntactical sugur. makes easier to understand the code instead of writing basic stuff .then() shows that when ever the task is done pls callback a anaother function .catch() shows if err comes pls call another function and these then and catch is a function installed in the promise class itself</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACPqc_IohzNGz33dW9ubXQ.png" /></figure><p>Would love to discuss more on my future vlogs………goodnight everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d784c9e4c86" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>