<?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"><channel><title><![CDATA[Bewafa-Promises Js]]></title><description><![CDATA[Bewafa-Promises Js]]></description><link>https://bewafa-promises-js.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 09 Oct 2026 16:31:18 GMT</lastBuildDate><atom:link href="https://bewafa-promises-js.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Bewafa Promises JS 💔]]></title><description><![CDATA[Introduction
Did you hear the word Promise? what comes to your mind ??
May be u will think about your THE ONE that verbally committed to you some thing 🥲. But You have no idea that their commitment w]]></description><link>https://bewafa-promises-js.hashnode.dev/bewafa-promises-js</link><guid isPermaLink="true">https://bewafa-promises-js.hashnode.dev/bewafa-promises-js</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[promises]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Arijit Kundu]]></dc:creator><pubDate>Sun, 01 Mar 2026 14:34:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6950e81e2f9daf13464777e3/a509cb71-93dc-4487-b41e-25abae6041ab.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Did you hear the word Promise? what comes to your mind ??</p>
<p>May be u will think about your THE ONE that verbally committed to you some thing 🥲. But You have no idea that their commitment will be fulfilled or not.</p>
<blockquote>
<p>Aao Ge Tum Kabhi Meri jaan Kahe rahi ...</p>
</blockquote>
<p>But But But, In JavaScript The Promises are a little different.</p>
<p>In JS you actually know what is the state of promises are unlike your THE ONE</p>
<h2>To Promise Hai Kya?</h2>
<p>A JavaScript Promise represents a value that may not be available yet. It's a core concept for handling asynchronous operations, which are tasks that don't complete immediately. These include common operations like:</p>
<ul>
<li><p>API requests (e.g., <code>fetch</code>)</p>
</li>
<li><p>Database queries</p>
</li>
<li><p>File operations</p>
</li>
</ul>
<p>(Without Promises, JavaScript's single-threaded nature would cause the entire application to freeze while waiting for these slow operations to finish. Promises allow JavaScript to continue executing other code while waiting for an asynchronous operation to complete.)</p>
<h2>States of Your JS Promises:</h2>
<p>Let's Go with your THE ONE 💔</p>
<p>Let's Assume, You confessed to your THE ONE last night but she didn't replied yet</p>
<ul>
<li><em>pending</em>: initial state, neither fulfilled nor rejected.</li>
</ul>
<p>Next Case... THE ONE replied 'I think you are my best friend and I am not into these stuffs right now' (Narrator: VAI TEREKO FRIENDZONE KAR DIYA LOL)</p>
<ul>
<li><em>rejected</em>: meaning that the operation failed.</li>
</ul>
<p>Last Case(In Your Dreams): 'I like You TOO'</p>
<ul>
<li><em>fulfilled</em>: meaning that the operation was completed successfully.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6950e81e2f9daf13464777e3/11de4da1-29a6-4c44-b9ef-d90f37c57a70.png" alt="" style="display:block;margin:0 auto" />

<h2>Basic Syntax of Promise (How to create one)</h2>
<p>You can create your own Promises using the <code>Promise</code> constructor. The constructor takes a single argument: a function called the <strong>executor</strong>. The executor function itself receives two parameters: <code>resolve</code> and <code>reject</code>.</p>
<ul>
<li><p><code>resolve(value)</code>: Call this function when the asynchronous operation succeeds. The <code>value</code> passed to <code>resolve</code> will be the result of the Promise.</p>
</li>
<li><p><code>reject(reason)</code>: Call this function when the asynchronous operation fails. The <code>reason</code> (usually an <code>Error</code> object) will indicate why the Promise was rejected.</p>
</li>
</ul>
<pre><code class="language-javascript">const KehDoHaa = new Promise((resolve, reject) =&gt; {
    const TheOne = true;

    setTimeout((bat bani) =&gt; {
        if (TheOne) {
            resolve("Man jayegi");
        } else {
            reject("Error: mana kar diya, Moye Moye");
        }
    }, 2000);
});
</code></pre>
<p><code>setTimeout()</code> it's a JavaScript time bomb. (Code Fat-ta nhi hai daro maat)</p>
<p>It doesn't stop the code from running; it just tells the browser to execute a specific piece of code once a certain amount of time has passed.</p>
<h2><strong>Handling Promise Outcomes</strong></h2>
<p>You use the <code>.then()</code>, <code>.catch()</code>, and <code>.finally()</code> methods to handle the outcome of a Promise.</p>
<h3><code>.then(onFulfilled, onRejected)</code></h3>
<ul>
<li><p>The <code>onFulfilled</code> callback function is executed if the Promise is <strong>fulfilled</strong>. It receives the resolved <code>value</code> as an argument.</p>
</li>
<li><p>The <code>onRejected</code> callback function (optional) is executed if the Promise is <strong>rejected</strong>. It receives the rejection <code>reason</code> as an argument.</p>
</li>
</ul>
<h3><code>.catch(onRejected)</code></h3>
<ul>
<li>This method is syntactic sugar for <code>.then(undefined, onRejected)</code>. It's used specifically to handle <strong>rejected</strong> Promises. The <code>onRejected</code> callback receives the rejection <code>reason</code> as an argument.</li>
</ul>
<h3><code>.finally(onFinally)</code></h3>
<ul>
<li>The <code>onFinally</code> callback function is executed regardless of whether the Promise was <strong>fulfilled</strong> or <strong>rejected</strong>. It's useful for cleanup tasks (e.g., stopping a loading spinner) that need to happen no matter the outcome.</li>
</ul>
<pre><code class="language-javascript">const KehDoHaa = new Promise((resolve, reject) =&gt; {
  const TheOne = false; 

  if (TheOne) {
    resolve("man gai");
  } else {
    reject("Error: mana kar diya, Sab Khatam");
  }
});

TheOne
  .then((bat chit) =&gt; {
    // Only runs if resolved
    console.log(message); 
  })
  .catch((error) =&gt; {
    // Only runs if rejected
    console.log(error); 
  })
  .finally(() =&gt; {
    // Runs no matter what
    console.log("Haa Main Ruka Hun Tu Ja Chuki Hai ..."); 
  });
</code></pre>
<h2><strong>Promises with</strong> <code>fetch</code></h2>
<p>The <code>fetch</code> API is a common example of an asynchronous operation that returns a Promise.</p>
<pre><code class="language-javascript">fetch('https://api.example.com/data')
  .then(response =&gt; {
    // The 'response' object is an HTTP response wrapper, not the data itself.
    // Check if the response was successful (e.g., status code 200-299).
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    // response.json() also returns a Promise that resolves with the JSON data.
    return response.json();
  })
  .then(data =&gt; {
    // 'data' is now the JavaScript object parsed from the JSON response.
    console.log("Received data:", data);
    // You can now work with the 'data' object.
  })
  .catch(error =&gt; {
    console.error("Fetch error:", error);
  })
  .finally(() =&gt; {
    console.log("Fetch operation finished.");
  });
</code></pre>
<h2><code>async</code><strong>/</strong><code>await</code> <strong>Syntax</strong></h2>
<blockquote>
<p>“Aaj nahin to kal — saare vaade (Promises) pure ho hi jayenge.”<br />Promise pehle <strong>Pending</strong> mein rahega.<br /><code>async</code> ka saath, <code>await</code> ke baad hum Promise ka result paayenge — ya to <strong>Fulfilled</strong> (vaada nibha gaya) ya <strong>Rejected</strong> (vaada toda gaya).<br />Aur jaise Tu keh raha hai: <em>“Haa Main Ruka Hun Tu Ja Chuki Hai”</em> — yeh Promise ka resolve value hai.</p>
</blockquote>
<p><code>async</code>/<code>await</code> is a modern syntax for working with Promises that makes asynchronous code look more like synchronous code.</p>
<h3><code>async</code> <strong>Keyword</strong></h3>
<ul>
<li><p>When you add <code>async</code> before a function declaration, it signifies that the function will always return a Promise.</p>
</li>
<li><p>If the function returns a value, JavaScript automatically wraps it in a resolved Promise.</p>
</li>
<li><p>If the function throws an error, it becomes a rejected Promise.</p>
</li>
</ul>
<h3><code>await</code> <strong>Keyword</strong></h3>
<ul>
<li><p>The <code>await</code> keyword can only be used inside an <code>async</code> function.</p>
</li>
<li><p>It pauses the execution of the <code>async</code> function until the Promise it's called on is settled (either fulfilled or rejected).</p>
</li>
<li><p>If the Promise is fulfilled, <code>await</code> returns the resolved value.</p>
</li>
<li><p>If the Promise is rejected, <code>await</code> throws the rejection reason as an error.</p>
</li>
</ul>
<p><strong>Important Note:</strong> <code>await</code> pauses the execution <em>within the</em> <code>async</code> <em>function</em>, not the entire JavaScript thread. This means other code outside of the <code>async</code> function can continue to run while the <code>await</code> is waiting.</p>
<h3><strong>Error Handling with</strong> <code>async</code><strong>/</strong><code>await</code></h3>
<p>Because <code>await</code> throws an error when a Promise rejects, you typically wrap <code>await</code> calls in a <code>try...catch</code> block to handle potential errors.</p>
<pre><code class="language-javascript">async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json(); // Await the Promise from response.json()
    console.log("Received data:", data);
    // Process data...
  } catch (error) {
    console.error("Fetch error:", error);
  } finally {
    console.log("Fetch operation finished (async/await).");
  }
}
fetchData();
</code></pre>
<h3><code>async</code><strong>/</strong><code>await</code> <strong>and</strong> <code>.finally()</code></h3>
<p>The <code>.finally()</code> method can also be used with <code>async</code>/<code>await</code> syntax, often within a <code>try...catch...finally</code> block, to execute code regardless of the outcome.</p>
<pre><code class="language-javascript">async function performOperation() {
  let isLoading = true; // Example: a loading state

  try {
    console.log("Starting operation...");
    const result = await somePromiseThatResolvesOrRejects();
    console.log("Operation successful:", result);
  } catch (error) {
    console.error("Operation failed:", error);
  } finally {
    isLoading = false; // Always set isLoading back to false
    console.log("Operation finished. Loading state:", isLoading);
  }
}
</code></pre>
<h2><strong>Callbacks</strong></h2>
<p>Before Promises, we used <strong>callbacks</strong>. If you had to do five things in a row, you ended up with "Callback Hell", a pyramid of nested functions that was impossible to read or debug.</p>
<p><strong>Promises solve this by:</strong></p>
<ul>
<li><p><strong>Chaining:</strong> You can return a new promise inside a <code>.then()</code> to create a flat sequence of events.</p>
</li>
<li><p><strong>Error Handling:</strong> A single <code>.catch()</code> at the end can handle errors from any step in the chain.</p>
</li>
</ul>
<h1>Methods in Promises</h1>
<p>This section explains the common Promise methods you’ll use in real-world JavaScript, what they do, and small examples that show the typical patterns and pitfalls.</p>
<hr />
<h2><code>.then(onFulfilled, onRejected)</code></h2>
<p>Attach handlers for a fulfilled value or an immediate rejection. Returns a <strong>new Promise</strong>, enabling chaining.</p>
<ul>
<li><p>If you return a value from <code>onFulfilled</code>, the next <code>.then</code> receives that value.</p>
</li>
<li><p>If you return a Promise, the next step waits for it to settle.</p>
</li>
<li><p>Prefer <code>.then(...).catch(...)</code> rather than passing <code>onRejected</code> to <code>.then</code> to keep error handling centralized.</p>
</li>
</ul>
<pre><code class="language-javascript">fetchData()
  .then(result =&gt; {
    // transform and pass to the next .then
    return result.items.length;
  })
  .then(count =&gt; {
    console.log('Items:', count);
  })
  .catch(err =&gt; {
    console.error('Error anywhere in the chain:', err);
  });
</code></pre>
<hr />
<h2><code>.catch(onRejected)</code></h2>
<p>Sugar for <code>.then(null, onRejected)</code>. Use it to handle errors from any previous step in the chain. If you want a final centralized error handler, put <code>.catch()</code> at the end of the chain.</p>
<pre><code class="language-javascript">doTask()
  .then(step1)
  .then(step2)
  .catch(err =&gt; {
    console.error('Handled error:', err);
  });
</code></pre>
<hr />
<h2><code>.finally(onFinally)</code></h2>
<p>Runs once the promise settles (fulfilled or rejected). Useful for cleanup (hide loaders, release resources). <strong>Important:</strong> <code>onFinally</code> does not receive the promise value or reason; it also does not alter the chain’s resolved value unless it throws an error or returns a rejecting promise.</p>
<pre><code class="language-javascript">showSpinner();
doWork()
  .then(result =&gt; console.log(result))
  .catch(err =&gt; console.error(err))
  .finally(() =&gt; {
    hideSpinner(); // runs whether success or failure
  });
</code></pre>
<hr />
<h2><code>Promise.resolve(value)</code> and <code>Promise.reject(reason)</code></h2>
<p>Create already-settled promises. Handy in functions that must return a Promise but sometimes have synchronous results.</p>
<pre><code class="language-javascript">function cachedData() {
  if (cacheFound) return Promise.resolve(cache);
  return fetchFromServer();
}
</code></pre>
<hr />
<h2><code>Promise.all(iterable)</code></h2>
<p>Waits for <strong>all</strong> promises to fulfill; resolves to an array of results in order. If <strong>any</strong> promise rejects, <code>Promise.all</code> rejects immediately with that reason. Good for parallel work when all results are required.</p>
<pre><code class="language-javascript">Promise.all([p1, p2, p3])
  .then(([r1, r2, r3]) =&gt; console.log(r1, r2, r3))
  .catch(err =&gt; console.error('One failed:', err));
</code></pre>
<p><strong>Pitfall:</strong> a single slow or failing promise blocks or rejects the whole group.</p>
<hr />
<h2><code>Promise.race(iterable)</code></h2>
<p>Settles as soon as any input promise settles (whether fulfilled or rejected). Useful for timeouts or taking the fastest source.</p>
<pre><code class="language-javascript">const timeout = new Promise((_, reject) =&gt; setTimeout(() =&gt; reject('timeout'), 2000));
Promise.race([fetchData(), timeout])
  .then(data =&gt; console.log('Got data:', data))
  .catch(err =&gt; console.error(err)); // either fetch error or 'timeout'
</code></pre>
<hr />
<h2><code>Promise.allSettled(iterable)</code></h2>
<p>Waits for <strong>all</strong> promises to settle and returns an array of result objects: <code>{ status: 'fulfilled', value }</code> or <code>{ status: 'rejected', reason }</code>. Use it when you need the outcome of every promise regardless of success/failure.</p>
<pre><code class="language-javascript">Promise.allSettled([p1, p2, p3])
  .then(results =&gt; {
    results.forEach(r =&gt; console.log(r.status, r.value ?? r.reason));
  });
</code></pre>
<hr />
<h2><code>Promise.any(iterable)</code></h2>
<p>Resolves as soon as the <strong>first promise fulfills</strong>. If all input promises reject, it rejects with an <code>AggregateError</code>. Use when you want the first successful result (e.g., multiple mirrors/replicas).</p>
<pre><code class="language-javascript">Promise.any([mirror1(), mirror2(), mirror3()])
  .then(firstSuccess =&gt; console.log(firstSuccess))
  .catch(aggregateErr =&gt; console.error('All failed:', aggregateErr));
</code></pre>
<hr />
<h2>Patterns &amp; Best Practices</h2>
<ul>
<li><p><strong>Return from</strong> <code>.then</code> to continue the chain (either a plain value or a Promise).</p>
</li>
<li><p><strong>Place</strong> <code>.catch()</code> <strong>at the end</strong> of the chain for centralized error handling.</p>
</li>
<li><p>Use <code>.finally()</code> for cleanup (UI spinners, releasing locks) but don’t rely on it to transform values.</p>
</li>
<li><p>Choose <code>Promise.all</code> when you <strong>need every result</strong>; choose <code>Promise.any</code> or <code>race</code> when you need the <strong>fastest success</strong>; use <code>allSettled</code> when you must <strong>inspect every result</strong>.</p>
</li>
<li><p>Avoid unhandled rejections — always handle errors or rethrow intentionally.</p>
</li>
</ul>
<hr />
<h1>Conclusion</h1>
<p>A <strong>Promise</strong> is a JavaScript object that stands in for the outcome of an async task — it starts <strong>pending</strong>, and then becomes either <strong>fulfilled</strong> (success) or <strong>rejected</strong> (failure).</p>
<p>Promises (and <code>async</code>/<code>await</code>) let you write non-blocking code that reads like synchronous code. They give clear, structured hooks for handling results (<code>.then</code>) and errors (<code>.catch</code> or <code>try</code>/<code>catch</code> with <code>await</code>).</p>
<p>Practice chaining results and centralizing error handling so your asynchronous code is predictable, easy to follow, and less likely to leak unhandled rejections.</p>
<p>Lastly for You Brother:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6950e81e2f9daf13464777e3/e3369854-62d1-4500-8699-12c6a3eeb470.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item></channel></rss>