This content originally appeared on DEV Community and was authored by Poornima Gowda
In javascript, promises are one of the techniques to deal with asynchronous operations that introduced in the ES6. If you are working on like fetching data or waiting for timer using setTimeout method, much easier to manage and more readable.
What is Promises?
A promise is an object that represents the eventual completion/ failure of an asynchronous operation and its resulting value. it can be in one of three states.
1.Pending: The initial state, Operation is ongoing, neither
fulfilled nor rejected.
2.Fulfilled: The operation completed successfully.
3.Rejected: The operation failed.
Syntax
Firstly, we have to use a constructor to create a Promise object by using new Promise(),This is called executor. It takes a single function with two parameters: resolve() and reject().
And resolve is executed when the operation is successful. Otherwise, reject is executed when operation fails.
Consuming process:
So, we can't access promises directly, to handle the promise result we have to use .then() & .catch() method
.then() - It is used to handle the result of a Promise once it has been resolved (successfully completed) or rejected (failed).
.catch() - This method is invoked when promise is rejected or some error has occurred in execution. This method is used for handling errors.
This content originally appeared on DEV Community and was authored by Poornima Gowda

Poornima Gowda | Sciencx (2024-08-20T06:01:33+00:00) Promises In Javascript. Retrieved from https://www.scien.cx/2024/08/20/promises-in-javascript-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.