a blog for those who code

Wednesday 9 December 2015

What is Promise in context of Node.js

In this post we will be discussing about Promise in context of Node.js. The best part of using Promise is that it provides an alternative to raw callbacks when dealing with asynchronous code. Promise is an object returned by asynchronous function which represents the result of the operation.

Promise is pending when the asynchronous operation is not yet completed, it's fulfilled when the operation successfully completed and rejected when the operation terminates with an error.

Promise Syntax

new Promise(function(resolve, reject) { ... });

In the above syntax we have a function object with two arguments resolve and reject. The first argument fulfills the promise whereas the second argument rejects it. To receive the fulfillment value or the error(reason of rejection), we can use the then() method of the promise as shown below.


promise.then([onFulFilled], [onRejected]); Where onFulFilled() is a function that will eventually receive the fullfillment value of the promise and onRejected() is another function that will receive the reason of the rejection as shown below. Both functions are optional.

One of the property of then() method is that it synchronously returns another promise which allows us to bind chains of promises, allowing easy aggregation and arrangement of asynchronous operations in several configurations. But the onFulfilled() and onRejected() functions are guaranteed to be invoked asynchronously even if our then() method is synchronous.

The best part is if an exception is thrown from onFulFilled() or onRejected() handler, the promise returned by the then() method will reject with the exception as the rejection reason.

Methods of Promise Object

1. resolve(value) - It creates new promise from value
2. reject(error) - It creates new promise that rejects with error as the reason
3. all(array) - It creates a promise that fulfill the array of fulfillments and reject it if any item of array rejects.

In our next post we will be discussing about how to use Promise in Node.js. Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment