Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Understanding Promises
3.
What is Promise .then() Function?
4.
Syntax of Promise .then() in JavaScript
5.
Example
6.
Parameters of Promise .then() in JavaScript
7.
Return Value of Promise .then() in JavaScript
8.
What is Chaining .then()?
9.
Frequently Asked Questions
9.1.
Can you chain .then() in JavaScript?
9.2.
What does .then() return?
9.3.
Is JS then synchronous?
10.
Conclusion
Last Updated: Apr 20, 2024
Easy

Promise .then() Function in JavaScript

Author Sinki Kumari
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

If you've worked with JavaScript for any length of time, you've likely encountered Promises. These are JavaScript objects that link the producing code and the consuming code together. They are used for handling asynchronous operations, allowing you to organize your asynchronous JavaScript code in a more synchronous fashion. 

Promise .then() Function in JavaScript

The .then() function is an essential part of this structure, and understanding it can vastly improve your JavaScript skills.

Understanding Promises

Before we jump into .then(), let's quickly revisit what a Promise in JavaScript is. A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, it's a returned object to which you attach callbacks, instead of passing callbacks into a function.

A Promise is in one of these states:

  • Pending: the Promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.
     
  • Fulfilled: the asynchronous operation has completed, and the Promise has a resulting value.
     
  • Rejected: the asynchronous operation failed, and the Promise will never be fulfilled. In the rejected state, a Promise has a reason that indicates why the operation failed.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Promise .then() Function?

The then() function is a fundamental part of JavaScript Promises. Promises are objects representing the eventual completion or failure of an asynchronous operation, and they allow you to handle asynchronous operations in a more elegant and organized way compared to traditional callback functions.

When you create a Promise, it typically performs some asynchronous operation, such as fetching data from a server or reading a file from disk. You can attach one or more then() methods to a Promise, which allows you to specify what should happen when the Promise is resolved (successfully completed) or rejected (encountered an error).

Syntax of Promise .then() in JavaScript


promise.then(onFulfilled[, onRejected]);

The .then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

Example

let promise = new Promise(function(resolve, reject) {

setTimeout(() => resolve("Done!"), 1000);
});

promise.then(
  result => console.log(result), // shows "Done!" after 1 second
  error => console.log(error) // doesn't run
);

Output 

Output

In this example, after the promise is resolved, it then triggers the onFulfilled function to log the result to the console.

Parameters of Promise .then() in JavaScript

The then() method in JavaScript Promises typically accepts two callback functions as parameters: onFulfilled and onRejected.

  • onFulfilled: This parameter is a function that will be called when the Promise is resolved successfully. It takes the resolved value of the Promise as its argument. This function handles the successful outcome of the asynchronous operation.
  • onRejected: This parameter is a function that will be called when the Promise is rejected, either due to an error in the asynchronous operation or due to explicitly calling the reject() function inside the Promise constructor. It takes the reason for rejection (typically an error object) as its argument. This function handles errors or failures in the asynchronous operation.

Return Value of Promise .then() in JavaScript

The then() method of a Promise returns a new Promise. This returned Promise represents the result of the callback function passed to then(). If the callback function returns a value (or another Promise), the returned Promise will be resolved with that value. If the callback function throws an error or returns a rejected Promise, the returned Promise will be rejected with that error.

This behavior allows for chaining multiple asynchronous operations together, making it easier to manage asynchronous code.

What is Chaining .then()?

One of the key features of .then() is the ability to chain them together for complex Promise sequences. When a callback returns a value, it becomes the result of the whole Promise chain.

new Promise(function(resolve, reject) {
  setTimeout(() => resolve(1), 1000); 
})
.then(function(result) { 
  console.log(result); 
  return result * 2;
})
.then(function(result) { 
  console.log(result);
  return result * 2;
})
.then(function(result) {
  console.log(result);
  return result * 2;
});

Output

output

In this example, each .then() shows the result of the previous Promise and then returns a new value, which becomes the input for the next .then().

Frequently Asked Questions

Can you chain .then() in JavaScript?

Yes, .then() methods can be chained together to run multiple asynchronous operations sequentially.

What does .then() return?

The .then() method returns a Promise, which can be used to schedule further actions after the current Promise is settled.

Is JS then synchronous?

In JavaScript, the then() method of Promises is asynchronous. This means that the callback functions passed to then() are executed asynchronously, after the Promise is resolved or rejected, and they don't block the execution of the subsequent code.

Conclusion

The Promise .then() function in JavaScript is a powerful tool for handling asynchronous operations. It provides an easy-to-use, straightforward way to sequence and handle asynchronous events. Understanding how to use and chain .then() calls effectively can make your code cleaner, more readable, and easier to debug. This is just scratching the surface of what Promises and the .then() function can do, but we hope it serves as a helpful introduction to these critical JavaScript concepts.

To learn more about JavaScript, we recommend reading the following articles:

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Happy Coding!

Previous article
isNaN() in JavaScript
Next article
JavaScript Symbol
Live masterclass