Javascript promise chaining
Tags: javascript, programming, promise
Published: 2023-02-14 12:00:26

Javascript promise is a major addition to EcmaScript6 enabling you to work on asynchronous code in a clean and organized manner.

### Promise

> The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Source: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

Javascript promise represents the result of an asynchronous operation, it can be resolved with a `.then()` or rejected with a `.catch()` callbacks


### Promise Chaining
Javascript chaining is a process of nesting multiple asynchronous operations where the result of one operation is passed as input to another

Here is an example
```javascript

const firstPromise = new Promise((resolve, reject) => {
	setTimeout(() => {
		console.log("Resolving first promise")
		resolve();
	}, 2000)
});

firstPromise
.then(() => {
	console.log("First promise resolved")
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			console.log("Resolving Second promise")
			resolve()
		}, 2000)
	})
})
.then(() => {
	console.log("Second promise resolved")
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			console.log("Resolving Third promise")
			resolve()
		}, 2000)
	})
}).then(() => {
	console.log("Third promise resolved")
});
```

output
```javascript
//After 2 seconds
Resolving first promise
First promise resolved
//After 2 seconds
Resolving Second promise
Second promise resolved
//After 2 seconds
Resolving Third promise
Third promise resolved
```

In the above example, the `firstPromise` is resolved and logged after 2 seconds, then the second promise is returned and after 2 seconds it is resolved and it goes on for the third promise

This way, you can chain any number of promises together, creating a pipeline of asynchronous operations.

### Error handling
One of the benefits of promise chaining is you can use `.catch()` method to catch errors that occur at any point in the code.

```javascript
const firstPromise = new Promise((resolve, reject) => {
	setTimeout(() => {
		console.log("Resolving first promise")
		resolve();
	}, 2000)
});

firstPromise
.then(() => {
	console.log("First promise resolved")
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			console.log("Rejecting second promise")
			reject("ERROR: Rejecting promise")
		}, 2000)
	})
})
.then(() => {
	console.log("Second promise resolved")
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			console.log("Resolving Third promise")
			resolve()
		}, 2000)
	})
}).then(() => {
	console.log("Third promise resolved")
}).catch((error) => {
	console.error("Error in promise chain")
})
``` 

Output

```javascript
//After 2 seconds
Resolving first promise
First promise resolved
//After 2 seconds
Rejecting second promise
Error in promise chain
```
In the above example, we rejected the promise after resolving the `firstPromise` hence `Error in promise chain` is logged and the chain broke


## Conclusion
JavaScript Promise Chaining is a powerful technique that allows developers to handle complex asynchronous operations in a simple, readable, and manageable way. By chaining promises together, you can break down complex operations into smaller steps, making your code easier to understand and debug. Additionally, promise chaining allows for code re-usability and helps you write more maintainable code.


## Try it yourself
Try to find the output of this below code. Don't execute code immediately, try to find and compare the output by executing  

```javascript
const firstPromise = new Promise((resolve, reject) => {
	setTimeout(() => {
		resolve();
	}, 2000)
});

firstPromise
.then(() => {
	console.log("First promise resolved")
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve()
		}, 2000)
	})
}).then(() => {
	console.log("Second promise resolved")
}).catch((error) => {
	console.error(error)
});


firstPromise.then(()=>{
    console.log("First promise resolved in second chain")
})
```

---
Please leave a like and share your thoughts in the comments section

<center>HAPPY CODING</center>

---

Cover photo by <a href="https://unsplash.com/@mikezo?utm_source=dev.to&utm_medium=referral&utm_content=creditCopyText">Mike Alonzo</a> on <a href="https://unsplash.com/photos/Xe7za0JtTeM?utm_source=dev.to&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>