DEV Community

Cover image for dfgdgd
Web2 Store
Web2 Store

Posted on • Edited on

dfgdgd

🔹 What is a Promise?

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A Promise has 3 states:

  1. Pending – Initial state, neither fulfilled nor rejected.
  2. Fulfilled – The operation completed successfully.
  3. Rejected – The operation failed.
const promise = new Promise((resolve, reject) => {
  // async operation
});
Enter fullscreen mode Exit fullscreen mode

🔹 Basic Example

const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const success = true;
      if (success) {
        resolve('Data fetched!');
      } else {
        reject('Error fetching data.');
      }
    }, 1000);
  });
};

fetchData()
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

🔹 Chaining Promises

const step1 = () => Promise.resolve('Step 1');
const step2 = prev => Promise.resolve(`${prev} → Step 2`);
const step3 = prev => Promise.resolve(`${prev} → Step 3`);

step1()
  .then(step2)
  .then(step3)
  .then(result => console.log(result)); // "Step 1 → Step 2 → Step 3"
Enter fullscreen mode Exit fullscreen mode

🔹 Error Handling in Chains

Promise.resolve('Start')
  .then(() => {
    throw new Error('Something went wrong');
  })
  .then(() => {
    console.log('This will not run');
  })
  .catch(error => {
    console.error('Caught error:', error.message);
  });
Enter fullscreen mode Exit fullscreen mode

🔹 Promise.all()

Runs multiple promises in parallel and waits for all to finish.

const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);

Promise.all([p1, p2, p3])
  .then(values => {
    console.log(values); // [1, 2, 3]
  });
Enter fullscreen mode Exit fullscreen mode

If any promise rejects, the whole Promise.all() rejects.


🔹 Promise.race()

Returns the first settled promise (either fulfilled or rejected).

const p1 = new Promise(resolve => setTimeout(() => resolve('Fast'), 500));
const p2 = new Promise(resolve => setTimeout(() => resolve('Slow'), 1000));

Promise.race([p1, p2]).then(result => {
  console.log(result); // "Fast"
});
Enter fullscreen mode Exit fullscreen mode

🔹 Promise.allSettled()

Waits for all promises to settle, regardless of their outcome.

const p1 = Promise.resolve('Success');
const p2 = Promise.reject('Failure');

Promise.allSettled([p1, p2]).then(results => {
  console.log(results);
});
Enter fullscreen mode Exit fullscreen mode

Output:

[
  { status: 'fulfilled', value: 'Success' },
  { status: 'rejected', reason: 'Failure' }
]
Enter fullscreen mode Exit fullscreen mode

🔹 Promise.any()

Returns the first fulfilled promise, ignores rejections.

const p1 = Promise.reject('Fail');
const p2 = Promise.resolve('Pass');
const p3 = Promise.resolve('Another Pass');

Promise.any([p1, p2, p3])
  .then(result => console.log(result)); // "Pass"
Enter fullscreen mode Exit fullscreen mode

If all promises reject, it throws an AggregateError.


🔹 Async/Await: Syntactic Sugar

const asyncFunc = async () => {
  try {
    const data = await fetchData();
    console.log('Data:', data);
  } catch (err) {
    console.error('Error:', err);
  }
};
Enter fullscreen mode Exit fullscreen mode

✅ Under the hood, async functions always return a promise.


🔹 Creating Delay with Promises

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function run() {
  console.log('Wait for it...');
  await delay(2000);
  console.log('Done!');
}

run();
Enter fullscreen mode Exit fullscreen mode

🔹 Common Pitfalls

1. Not returning in .then()

// WRONG
fetchData()
  .then(data => {
    doSomething(data);
    // forgot to return
  })
  .then(more => console.log(more));

// CORRECT
fetchData()
  .then(data => {
    return doSomething(data); // chain continues properly
  })
  .then(more => console.log(more));
Enter fullscreen mode Exit fullscreen mode

2. Using try/catch without await

// WRONG
try {
  fetchData().then(data => console.log(data));
} catch (e) {
  console.error('Will not catch error!');
}
Enter fullscreen mode Exit fullscreen mode

🔹 Real-World Example: Fetch API

async function getUserData(userId) {
  try {
    const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
    if (!res.ok) throw new Error('User not found');
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

getUserData(1);
Enter fullscreen mode Exit fullscreen mode
Month Savings
January $250
February $80
March $420

Top comments (3)

Collapse
 
web2_store_32e39cb2e4f348 profile image
Web2 Store

sdfsd

Collapse
 
web2_store_32e39cb2e4f348 profile image
Web2 Store

new

Collapse
 
web2_store_32e39cb2e4f348 profile image
Web2 Store

sfd