How does the JavaScript Promise work?

Promise

A Promise is an object representing the eventual completion or failure of an asynchronous operation. A JavaScript Promise object contains both the producing code and calls to the consuming code. It can be used to deal with Asynchronous operations in JavaScript.

Promise State:-

Pending – Initial State, Not yet Fulfilled or Rejected
Fulfilled/Resolved – Promise Completed
Rejected – Promise Failed

How Promise works

  • A pending promise can either be Resolved with a value or Rejected with a reason (error).
  • When either of these options happens, the associated handlers queued up by a promise’s then method are called.
  • A promise is said to be settled if it is either Resolved or Rejected, but not Pending.

Creating Promise

Promise () – A Promise object is created using the new keyword and its constructor. This constructor takes a function, called the “executor function”, as its parameter. This function should take two functions as parameters. The first of these functions (resolve) is called when the asynchronous task completes successfully and returns the results of the task as a value. The second (reject) is called when the task fails and returns the reason for failure, which is typically an error object.

Syntax:- Promise (executor)

A JavaScript Promise object contains both the producing code and calls to the consuming code.

Function Returning a Promise

then( ) Method

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise. As then the method returns a Promise so we can do method chaining.

Syntax:- then(onResolved, onRejected)

onResolved – A Function called if the Promise is fulfilled. This function has one argument, the fulfillment value.

onRejected – A Function called if the Promise is rejected. This function has one argument, the rejection reason.

Promise

Chaining

The then method returns a Promise which allows for method chaining. If the function passed as a handler to then returns a Promise, an equivalent Promise will be exposed to the subsequent then in the method chain.

catch () Method

The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling then(undefined, onRejected). In fact, calling catch(onRejected) internally calls then(undefined, onRejected).

The catch method is used for error handling in promise composition. Since it returns a Promise, it can be chained in the same way as its sister method, then()

Syntax:- catch(callback)

Where the callback is a function called when the Promise is rejected. This function has one argument error – The rejection error.

catch () Method

finally () Method

The finally() method returns a Promise. When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with.

This helps to avoid duplicating code in both the promise’s then() and catch() handlers.

Syntax:- finally(callback)

finally () Method

Chaining

Tagged : / / / /

JavaScript Cheat Sheet — JSON, Loops, and Promises

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript

JSON

We can create JSON strings from JavaScript objects with the JSON.stringify method:

And we can convert JSON strings back to JavaScript objects with JSON.parse :

const obj = JSON.parse(json);

We can use it to store data in local storage.

We’ve to convert objects into strings first to store them.

To store objects we call localStorage.setItem :

The first argument is the key.

And we can get data by their keys with getItem :

localStorage.getItem(‘json’)

Loops

avaScript comes with various kinds of loops.

One kind of loop is the for loop:

for (let i = 0; i < 10; i++) { console.log(i); }

We can loop through any kind of iterable object with the for-of loop:

for (let i of custOrder) { console.log(i); }

Some iterable objects include arrays, strings, and node lists.

Another kind of loop is the while loop:

There’s also the do-while loop:

The break keyword lets us end the loop early:

The continue keyword lets us skip to the next iteration:

Data Types

JavaScript comes with various data types.

They include:

Objects

We can create an object with curly braces:

It has properties and methods.

this is the student object itself.

We can call fullName with student.fullName() .

And we can assign values to properties with:

student.age = 19;

Promises

We can create promises with the Promise constructor:

We can resolve to fulfill the promise with the sum.

And we call reject to reject the promise with an error.

Then we can call then to get the resolved value and catch to get the error values:

Conclusion

We can work with JSON, local storage, promises, and loops with JavaScript.

Tagged : / / /