First thing first!
When do we use async method or why do we use async method?
Answer – When we want to make sure one call/request is complete and data (if any) from that call is received before we move to next call, in that case we create an asynchronous arrangement.
Now let’s see how to use Promise keyword for handling asynchronous method.
We will use our async project that is stored at GitHub for this.
To run the project, simply open the test.html from the project and run it in the browser.
new Promise(resolve, reject)Let’s understand how it works: In the value of resolve variable, we pass a method which will be called when the main method returns a value (success case) and the value returned from the main method which is the student data in this case is passed to the resolve variable (the method), now it’s the duty of the resolve method to show success message in the output. In case our main method fails which means our API failed to get the student data we will have to raise an error, so the method which will actually raise an error is received in the reject parameter of the Promise method, we may raise an error directly also like using alert box in case of error, but using the reject variable (a method) is the norm in case of Promise. Once the resolve/reject method receives its data/output, it is passed to the then method in case of success or the catch method in case of failure. Complete code is below:
first the updateNewStudent method is called. Inside the method we create a Promise object and inside the promise object we are making an API call.
In case of success of the API call we are passing the result in the resolve param and in case of failure we are passing the result in the reject param.
Note: The actual code inside Promise is not called until the then method is called.
Output in browser will be like as shown below :-
I do not even understand how I ended up here, but I assumed this publish used to be great