codedamn

JavaScript Promise – What is it and how does it work?

JavaScript Promise – What is it and how does it work?

Hey readers, in this article, we will be covering all about promise in JavaScript and its working along with examples. Before jumping directly to the working part, we will learn about JavaScript and the basics of what exactly promises in JavaScript. So if you are new to all these concepts, don’t worry, we will be covering it right from the fundamentals and will then move to differences. So keep reading.

Live New Year Sale. Become The Best JavaScript Developer 🚀
Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.
  • Free money-back guarantee
  • Unlimited access to all platform courses
  • 100's of practice projects included
  • GPT-3 Based Instant AI Help
  • Structured Full-Stack Web Developer Roadmap To Get A Job
  • Exclusive community for events, workshops
Go Pro Now (50% Discount For Limited Time)

Introduction to promise in JS

In JavaScript, promises are used to handle asynchronous operations. When dealing with several asynchronous activities, where callbacks might cause callback hell and unmanageable code, they are simple to manage.

Prior to promises, callback functions and events were utilized, but they were limited in functionality and resulted in unmanageable code.

Callback hell would result from multiple callback functions, resulting in unmanageable code. In addition, managing several callbacks at the same time is difficult for any user.

Asynchronous operations were not well handled by events.

Promises are the best option for handling asynchronous tasks in the most straightforward way. They can easily handle many asynchronous operations and handle errors better than callbacks and events. In other words, promises are an excellent alternative for managing numerous callbacks at the same time, avoiding the undesirable callback hell condition.

Promises give a user a higher possibility of reading the code more effectively and efficiently, especially if the code is used to implement several asynchronous activities.

Advantages of using promise in JS

  • Enhances the readability of code
  • A better way to handle asynchronous operations
  • In asynchronous logic, a better flow of control definition is needed
  • Improved Error Handling

Important points to remember in JS:

  • It is a scripting language
  • It has unstructured code
  • It is a programming language
  • It is used both client-side and server-side to make web apps interactive
  • It is built and maintained by Brendan Eich and the team
  • Uses built-in browser DOM
  • Extension of JavaScript file is .js

States of promise in JS

There are four states to a promise:

fulfilled: Actions taken in response to the promise were rejected: The promise-related action failed pending: Promise is still pending, i.e. it hasn’t been fulfilled or refused, and it hasn’t been resolved: Promises have either been fulfilled or rejected.

The Promise constructor can be used to make a promise.

Promise Syntax in JavaScript

var promise = new Promise(function(resolve, reject){ //do something });
Code language: JavaScript (javascript)

Parameters

The promise function Object() { [native code] } only accepts one argument: a callback function (and that callback function is also referred as anonymous function too).

The resolve and refuse arguments are passed to the callback method.

Execute activities within the callback code, and then call resolve if everything went well.

Call reject if the desired operations do not go as planned.

Example

var promise = new Promise(function(resolve, reject) { const x = "codedamn"; const y = "codedamn" if(x === y) { resolve(); } else { reject(); } }); promise. then(function () { console.log('Success, You are a part of Codedamn); }). catch(function () { console.log('Some error has occurred'); });
Code language: JavaScript (javascript)

Using the .then and .catch methods, you can consume promises by registering functions.

1. When a promise is either resolved or refused, then() is called. It can also be characterized as a profession that takes data from a promise and successfully performs it.

Two functions are passed as inputs to the then() method.

If the promise is resolved and a result is obtained, the first function is called.

If the promise is refused and an error is received, the second function is called. ( It’s not required, and there’s a better approach to handle errors with. catch() is a method for catching something.

Syntax:

.then(function(result){ //handle success }, function(error){ //handle error })
Code language: JavaScript (javascript)

Examples of promise in JS

Example of Promise Resolved

var promise = new Promise(function(resolve, reject) { resolve('Codedamn'); }) promise .then(function(successMessage) { //success handler function is invoked console.log(successMessage); }, function(errorMessage) { console.log(errorMessage); }) catch()
Code language: JavaScript (javascript)

When a promise is either refused or an error occurs during execution, catch() is called. It’s utilized as an Error Handler if there’s a risk of obtaining an error at any phase.

The catch() method takes one parameter, which is a function.

Errors and promise rejections are handled by this function.

Internally, the.catch() method invokes.

.catch() is just a shortcut for then(null, errorHandler), i.e.

then(null, errorHandler)) Syntax: .catch(function(error){ //handle error })
Code language: JavaScript (javascript)

Examples: Promise Rejected

var promise = new Promise(function(resolve, reject) { reject('Promise Rejected') }) promise .then(function(successMessage) { console.log(successMessage); }) .catch(function(errorMessage) { //error handler function is invoked console.log(errorMessage); });
Code language: JavaScript (javascript)

Conclusion

This was all about the promise in JavaScript. If you have any query related to React or JavaScript, do drop it down in the comment section also do check out codedamn courses if you want to learn more about JavaScript and React with its use cases and amazing projects. They also have an in-built playground for different programming languages and environment sets so do check that out and join codedamn’s community! 

Hope you like it.

Live New Year Sale. Become The Best JavaScript Developer 🚀
Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.
  • Free money-back guarantee
  • Unlimited access to all platform courses
  • 100's of practice projects included
  • GPT-3 Based Instant AI Help
  • Structured Full-Stack Web Developer Roadmap To Get A Job
  • Exclusive community for events, workshops
Go Pro Now (50% Discount For Limited Time)

Learn programming on codedamn

Codedamn is an interactive coding platform with tons of sweet programming courses that can help you land your first coding job. Here's how:

Programming is one of the most in-demand jobs today. Learning to program can change your future. All the best!

Sharing is caring

Did you like what mansi wrote? Thank them for their work by sharing it on social media.