Promises in JavaScript:

Vchanduu
2 min readJan 3, 2021

JavaScript is predominantly single threaded . This makes it slow and restrictive . With the help of promises and other asynchronous concepts JavaScript can perform long network requests simultaneously without blocking the main thread.

Promises are the ideal choice for handling asynchronous operations in the simplest manner.

A Promise has four states:

  1. fulfilled: Action related to the promise succeeded
  2. rejected: Action related to the promise failed
  3. pending: Promise is still pending i.e not fulfilled or rejected yet
  4. settled: Promise has fulfilled or rejected

A promise can be created using Promise constructor.

  • Promise constructor takes only one argument a callback function.
  • Callback function takes two arguments, resolve and reject
  • Perform operations inside the callback function and if everything went well then call resolve.
  • If desired operations do not go well then call reject.

Output:

Success, Welcome to Masai tribe

Promise Consumers

Promises can be consumed by registering functions using .then and .catch methods.

then( )
then() is invoked when a promise is either resolved or rejected.
Parameters:
then() method takes two functions as parameters.

catch( )
catch() is invoked when a promise is either rejected or some error has occured in execution.
Parameters:
catch() method takes one function as parameter.

Below code snippet shows example

Benefits of Promises

  1. Improves Code Readability.
  2. Better handling of asynchronous operations.
  3. Better flow of control definition in asynchronous logic.
  4. Better Error Handling.

--

--