Promises in JavaScript

dilusha sandaruwani
3 min readMar 8, 2024

--

Promise is a good way to handle asynchronouns operations. It is used to find out if the asynchronous operation is successfully completed or not.

A promise may have one of three states.

  • Pending — process is not complete
  • Fulfiled — operation is successful
  • Rejected — an error occurs

Create A Promise

To create a promise object, we use the Promise() constructor.

if the promise returns successfully, the resolve() function is called.

And, if an error occurs, the reject() function is called.

Example

Let’s suppose that the program below is an asynchronous program.

Promise Chaining

Promises are useful when you have to handle more than one asynchronous task, one after another.

You can perform an operation after a promise is resolved using methods then(), catch() and fianlly().

then() Method

The then() method is used with the callback when the promise is successfully fulfiled or resolved.

You can chain multiple then() methods with the promise.

catch() Method

The catch() method is used with the callback when the promise is rejected or if an error occurs.

finally() method

The finally() method gets executed when the promise is either resolved successfully or rejected.

Promises Vs Observables

Promises:-

  • Emits only a single value at a time.
  • Eager in nature; they are going to be called immediately.
  • Promise is always asynchronous even though it resolved immediately.
  • Doesn’t provide any operators.
  • Cannot be cancelled.

Observables:-

  • Emits multiple values over a period of time.
  • Lazy in nature; they require subscription to be invoked.
  • Observable can be either synchronous or asynchronous.
  • Provides operators such as map, forEach, filter, reduce, retry, and retryWhen etc.
  • Cancelled by using unsubscribe() method.

--

--

dilusha sandaruwani
dilusha sandaruwani

Written by dilusha sandaruwani

Software Engineering undergraduate at University of Kelaniya

No responses yet