🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

.then() Method

AI & DATA SCIENCE // then

.then() handles a fulfilled Promise. It accepts an onFulfilled callback and an optional onRejected callback. Returns a new Promise.

Syntax

promise
  .then(value => { /* success */ })
  .then(next => { /* chain */ })
  .catch(err => { /* error */ });

Deep Dive Course

**.then()** is how you consume a resolved Promise value. Each `.then()` returns a **new Promise**, enabling **chaining**. The return value of a `.then()` callback becomes the resolved value of the next Promise in the chain. Throwing inside `.then()` rejects the next Promise.

1Understanding .then() Method

.then() is how you consume a resolved Promise value. Each .then() returns a new Promise, enabling chaining. The return value of a .then() callback becomes the resolved value of the next Promise in the chain. Throwing inside .then() rejects the next Promise.

💡

Return values from .then() callbacks are automatically wrapped in resolved Promises. Return a Promise to chain async operations.

editor.html
fetch('/api/user/1')
  .then(response => {
    if (!response.ok) throw new Error('Not found');
    return response.json(); // returns a Promise
  })
  .then(user => {
    return fetch(`/api/posts?userId=${user.id}`);
  })
  .then(res => res.json())
  .then(posts => console.log(posts.length))
  .catch(err => console.error(err));
localhost:3000

2Practical Example

Here is a real-world application of .then() Method showing how it is used in production JavaScript code.

editor.html
// then with both callbacks
const p = Math.random() > 0.5
  ? Promise.resolve('success')
  : Promise.reject(new Error('failure'));

p.then(
  value => console.log('Resolved:', value),
  error => console.log('Rejected:', error.message)
);
localhost:3000

3Best Practices

Follow these guidelines when working with .then() Method:

1. Always return values in .then() callbacks for proper chaining

2. Don't forget to return Promises inside .then()

3. Use .catch() at the end of chains to handle any rejection

⚠️

Tip: Return values from .then() callbacks are automatically wrapped in resolved Promises. Return a Promise to chain async operations.

editor.html
fetch('/api/user/1')
  .then(response => {
    if (!response.ok) throw new Error('Not found');
    return response.json(); // returns a Promise
  })
  .then(user => {
    return fetch(`/api/posts?userId=${user.id}`);
  })
  .then(res => res.json())
  .then(posts => console.log(posts.length))
  .catch(err => console.error(err));
localhost:3000

Examples

Example 01Basic Usage
fetch('/api/user/1')
  .then(response => {
    if (!response.ok) throw new Error('Not found');
    return response.json(); // returns a Promise
  })
  .then(user => {
    return fetch(`/api/posts?userId=${user.id}`);
  })
  .then(res => res.json())
  .then(posts => console.log(posts.length))
  .catch(err => console.error(err));
Example 02Advanced Example
// then with both callbacks
const p = Math.random() > 0.5
  ? Promise.resolve('success')
  : Promise.reject(new Error('failure'));

p.then(
  value => console.log('Resolved:', value),
  error => console.log('Rejected:', error.message)
);

Best Practices

  • Always return values in .then() callbacks for proper chaining
  • Don't forget to return Promises inside .then()
  • Use .catch() at the end of chains to handle any rejection

Interview Question

What happens if you return a value from inside .then()?

Hint: The return value becomes the next Promise's resolved value.

Returning a plain value from .then() wraps it in a resolved Promise automatically. Returning a Promise makes the chain wait for it. Throwing an Error rejects the next Promise. NOT returning anything returns undefined (which is often a bug in chains).

Exercises

MediumPractice using .then() Method in a real scenario.
View Solution
fetch('/api/user/1')
  .then(response => {
    if (!response.ok) throw new Error('Not found');
    return response.json(); // returns a Promise
  })
  .then(user => {
    return fetch(`/api/posts?userId=${user.id}`);
  })
  .then(res => res.json())
  .then(posts => console.log(posts.length))
  .catch(err => console.error(err));

Frequently Asked Questions

What happens if you return a value from inside .then()?

Returning a plain value from .then() wraps it in a resolved Promise automatically. Returning a Promise makes the chain wait for it. Throwing an Error rejects the next Promise. NOT returning anything returns undefined (which is often a bug in chains).

Related Functions

PromisescatchawaitfinallyJavaScript