Skip to main content

Command Palette

Search for a command to run...

JavaScript Promises

Updated
2 min readView as Markdown

“Dear JavaScript, even if I move on to fancier languages, I promise I won’t forget you."

In JavaScript operations that take time, are handled asynchronously. Promises were introduced to handle such asynchronous code by providing a cleaner and structured way to work.

Before promises were introduced, developers used to use callbacks to handle asynchronous operations. However, callbacks lead to callback hell which was difficult to handle, promises flatten this structure. Errors can be now caught easily using the .catch() method and .then() method helps in chaining and sequentially complete the task.

Promises have 3 states:

Pending: when the task has just begun

Fulfilled: task was successful

Rejected: task failed, error is returned

Eg. const promise = new Promise((resolve, reject) => {

let success = true;

if(success){

resolve("Operation Successful");

} else{

reject("Operation Rejected");

}

});

you need not necessarily use "resolve" and "reject", any word can be used. Resolve marks that the promise has been fulfilled while reject marks that the promise was rejected and throws an error.

Handling success and failure

Promises use .then() to handle the resolved value and .catch() is used to handle the errors.

Eg. promise

.then(result => {

console.log(result);

})

.catch(error => {

console.log(error);

});

promise.finally(() => {

console.log("Operation Completed");

});

Output: Operation Successful

Operation Completed

Promise {: 'Operation Successful'}

Promise chaining

Promises allow chaining of the code which in turn helps to execute a series of asynchronous operations in a sequence. It helps manage multiple operations at the same time. This also reduces the chance of callback hell because there is no need to use deeply nested functions.

Promise.resolve()

.then (onFulfilment1)

.then(onFulfilment)

.then(onFulfilment)

.catch(Rejected)

Benefits of promise chaining:

  • Cleaner code: avoids nested callbacks

  • Centralised error handling: one .catch() manages errors for all the chained code.

  • Easy Debugging since improved readability.

Difference between callbacks and promises:

Feature Callbacks Promises
Syntax Less readable (callback hell) Clean and structured
Error Handling Scattered Dedicated .catch()
Chaining Difficult Easy with .then()
Readability and Maintainability Less readable and hard to maintain More readable and easier to maintain