JavaScript Promises Explained for Beginners
JavaScript is single-threaded, meaning it can only do one thing at a time. But what if you need to fetch data from an API, read a file, or wait for a timer without freezing your app? This is where ...

Source: DEV Community
JavaScript is single-threaded, meaning it can only do one thing at a time. But what if you need to fetch data from an API, read a file, or wait for a timer without freezing your app? This is where promises come in. š§ What Problem Do Promises Solve? Before promises, we used callbacks for async tasks: ```js id="cb1" fetchData(function(data) { processData(data, function(result) { console.log(result); }); }); ā Callback hell ā hard to read, hard to maintain Promises simplify this by representing a **future value**: > A promise is like a placeholder for a value that **may not be available yet**. --- ## ā³ Promise States A promise can be in **three states**: 1. **Pending** ā initial state, waiting for the result 2. **Fulfilled** ā operation succeeded, value available 3. **Rejected** ā operation failed, error available ```id="viz1" Pending ā Fulfilled or Rejected āļø Basic Promise Lifecycle ```js id="promise1" const promise = new Promise((resolve, reject) => { const success = true; if (s