Introduction to Javascript Promises API

Javascript Promises API
Javascript Promises API - MDN

A Promise is a value not necessarily known at the time of it’s creation. It mainly used in asynchronous actions resulting in success or failure. The Promises represents a value which may be available now, or in the future, or never.

Promises

then() and catch() are prototype methods and they can ben chained as shown above. A Promise will always be either “Pending” or “Fulfilled” or “Rejected”.

  • Pending – Initial state, operation not started yet.
  • Fulfilled – Operation completed.
  • Rejected – Operation failed.

While synchronous code is easy to understand but sometime it leads to bad performance and not flexible enough as compared to asynchronous code. With async we can trigger more then one request unlike in sync and moreover the code will be clean & clear to understand.

Methods

Promise.all()

Returns a Promise once all the requests passed will resolves and rejects if any of the promises rejects. Let’s assume you have multiple requests and you want a callback only when all the requests resolve or rejects. Here comes the Promise.all(). It takes an Array of promises and fire one callback only when they all are resolved.

Promise.race()

Returns a Promise as & when any of the requests resolves. Unlike Promise.all(), this doesn’t wait to resolve all the requests passed as an Array in the Promise.race(). As soon the promise resolves it returns value from that promise. Syntax for this is same as above.

We can also use resolves() and reject() separately to get things done.

Conclusion

Now a days Promises API is getting into limelight and more & more developers are using in their projects. It’s bit hard to understand but once you get on with it, it will become habit to use in project.

Useful Link – Mozilla Developer Network

Ashish Panchal

Web/ UI & Front-end developer based in Ahmedabad, GJ, India. Here to help/ discuss community to spread web awareness.

You may also like...

1 Response

  1. January 3, 2017

    […] case you are interested to know more about Promises, I have published an article earlier on the […]

Leave a Reply

Your email address will not be published. Required fields are marked *