Promises enable us to carry out asynchronous transactions.
Imagine that you have a beautiful website that is fetching news from five different news sites. With a typical way of writing programs: you would have to fire off request to news1, wait for response & update your news posts, fire another request to news2, and so on.
This is inefficient
Instead, how about firing off five different requests to the sites. But, we don’t wait for them. We also tell the main thread (the fireball of event loop) to register call back functions to update news when and as we receive updated news. Meanwhile the fireball can chill.
As and when the said sites return the content, our ol’ faithful event loop updates news posts in our site. In summary: that is exactly what promises do.
Promises provide a mechanism in which you can initiate multiple requests, the program (or the main thread) continues to happily process the rest of the program, and once complete (i.e., when promise is resolved), a function is called. The call back function can update the news posts in your site.
You can also handle errors from promises (either in external systems or in call back functions), chain promises in a sequence, resolve multiple promises in one go (meaning wait for all promises to resolve), and in general go crazy on Promises.
Why to use promises?
If you are still left scratching your head on why would someone go through the pain of using promises, here are some basic guidelines
- Use promises to manage async transactions - these transactions do not demand priority handling or block the main thread. They go in coma and get revived when there is a response and call back processing is needed
- your client (the browser or API caller, not Dr. Alex Smith) wants to request data from server (e.g. get me user profile info), or from a third party site (get news & weather)
- you need to chain async transactions - use promise chaining
Promise is not the solution when -
- you are looking at blocking the main thread or you want the highest priority for the task