JavaScript Promises....


A promise represents the eventual result of an asynchronous operation. It is a placeholder into which the successful result value or reason for failure will materialize.

Promises provide a simpler alternative for executing, composing, and managing asynchronous operations when compared to traditional callback-based approaches. They also allow you to handle asynchronous errors using approaches that are similar to synchronous try/catch.


Promise States

Pending - the promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.
Fulfilled - the asynchronous operation has completed, and the promise has a value.
Rejected - the asynchronous operation failed, and the promise will never be fulfilled. In the rejected state, a promise has a reason that indicates why the operation failed.


When a promise is pending, it can transition to the fulfilled or rejected state. Once a promise is fulfilled or rejected, however, it will never transition to any other state, and its value or failure reason will not change.


How to use a promise.?


   The primary API for a promise is its then method, which registers callbacks to receive either the eventual value or the reason why the promise cannot be fulfilled. Here is a simple “hello world” program that synchronously obtains and logs a greeting.



However, if "sayHello" is asynchronous and needs to look up the current greeting from a web service, it may return a promise.


 The same message is printed to the console, but now other code can continue while the greeting is being fetched.

 As mentioned above, a promise can also represent a failure. If the network goes down and the greeting can’t be fetched from the web service, you can register to handle the failure using the second argument to the promise’s then method.


 Transforming Future Values

One powerful aspect of promises is allowing you to transform future values by returning a new value from callback function passed to then. For example



 Sequencing Asynchronous Operations

 A function passed to "then" can also return another promise. This allows asynchronous operations to be chained together, so that they are guaranteed to happen in the correct order. For example, if "addExclamation" is asynchronous (possibly needing to access another web service) and returns a promise for the new greeting.


Comments

Popular posts from this blog

Assignments and Grades integration in Moodle LMS - LTI 1.3 (With client_credentials base OAuth 2.0)

Cross Site Request Forgery Protection