Dear readers, this post is about a very useful and important concept of JavaScript. I think every beginner should have this basic knowledge while developing any project.
What is a Promise
In JavaScript, Promise
is a very important concept.The Promise object represents the eventual completion
or failure
of an asynchronous operation and its resulting value.
ππ» A Promise is a proxy with an unknown value whenever a Promise is generated.
ππ» This allows the controller to connect with the final success value or reason for failure of the asynchronous operation.
ππ» This allows asynchronous methods to return the same values ββas synchronous methods.
ππ»Instead of returning the final value immediately, the asynchronous method returns a promise to provide the value at a particular point in the future.
Basic Syntax
Promise is a constructor function, so we need a new
to create a Promise. It takes a function, as it's argument, with two parameters: resolve
and reject
.
The syntax generally looks like:
const myPromise = new Promise((resolve, reject) => { } ) ;
States of a Promise
A promise has three states:
i) pending
: It's the initial state, neither successful nor unsuccessful.
ii) fulfilled
: It means that the operation was completed successfully.
iii) rejected
: It indicates that the operation has failed.
Resolve Parameter
The resolve
parameter is used when we want the promise to succeed.
Reject Parameter
The reject
is used when we want to catch the failure.
The following is an example of a Promise:
const makeServerRequest = new Promise((resolve, reject) => {
let responseFromServer;
if (responseFromServer) {
resolve("We got the Data");
} else {
reject("Data not Found");
}
});
In the code snippet, responseFromServer represents a response from the server.
If responseFromServer is true, the resolve
method will be called to successfully complete the promise and return the string as it's argument.
(Generally, it returns data)
Again, if responseFromServer is false, the promise will fail and call the reject
method.
Top comments (10)
One thing you must know it's that an async function always returns a promise.
Yes.. My next post will be about that.
Is there a way to get states? Such as pending...?
Pending state starts while generating the promise, until it is either resolved or rejected. That means, until you get any result, successful or failure, the state is pending.
Well, if you working with React or React Native, in that case you can set the initial state as pending state, set resolve in then section and set reject in catch section. I'll write about it later in another post clearly.
You can use defualt state with pending string and then after resolve you can change state with resolve and in catch section set state with reject !
If you mean state in React π
Correct
Hey, as I am new to the platform, didn't know about this and couldn't understand your comment. Thank you so much. It works fine.
Perfect π
Thank you so much
Yes I got it now βΊοΈβΊοΈ