Problem
Although there are many ways to handle asynchronous methods, sometimes we get confused about how to handle asynchronous methods in JavaScript. Reason is, different methods, which are Promise, async await, then-catch methods produce similar result.

Solution
We will see different approaches of handling asynchronous methods in JavaScript and meaning of each term. This is the first blog on async calls, in this blog we will show how to make asynchronous call using Promise API(method), in other words this blog explains how to best use Promise API to make asynchronous calls.
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.
There are 5 .js files in the project, each JavaScript file is using different way of handling the async method. To see it in action we can simply change the source of .js in the test.html file. Current file name is promise.js
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:
When the JavaScript file gets loaded, it starts the execution from the try block,
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 :-

More from Node/Javascript:





Cheers
I do not even understand how I ended up here, but I assumed this publish used to be great