JavaScript is an asynchronous language which means that the script sends a request to the server and continue to execute the rest of the code without waiting a reply from the server. This behavior can cause a lot of confusions and problems in the code if the script depends on the server's reply. That's where Promises comes to our help.
Promise represents the eventual result of an asynchronous operation. Promise is part of ES6, and as you might guess Internet Explorer does not support it. Here is the Promises result from CanIUse
Promises sounds great, but since it doesn't work with Internet Explorer, we really can depend on it. As an alternative, we can use jquery to handle asynchronous calls. JQuery has $.when() function which works like promises and waits for async calls to finish to run the rest of your code.
Let's try to visualize asynchronous calls and see what's happens when we don't use Promises.To demonstrate the problem, I am calling an API 6 times in the following code. Our code needs to get the results of these 6 ajax calls to continue.
When I run this code, I get the following order. As you can see all the Ajax calls are getting completed after the code reaches to the end of the Load() function. That means if you are depending on the ajax call results, your code will fail.
Now, Let's see what Promises can do for us. Here is the syntax of Promises, we are passing a function with resolve and reject. Resolve contains the successful result, reject contains the information if something goes wrong.
new Promise(function(resolve, reject){})
A Promise has three states.
- Pending : Initial State, no other information is available in this state.
- Fulfilled : Operation completed successfully.
- Rejected : Operation is failed.
I have created following Promise to wait for the 6 ajax calls. When I call the resolve(current) in the following code, I change this Promise's state to Fulfilled.
Now, we need to call this function. In the following code, I am calling WithPromise() function with .then(function), Application runs the function we pass in then() when promise returns Fulfilled state.
Let's see the results when I call the Promise.
Now, my code which depends on the ajax calls, should not fail anymore. As you can see application waits for all ajax calls to finish to call the rest of the code.
You can see this code in action in my CodePen.
No comments:
Post a Comment