Introduction
This is the meaning of promise that I found on Bing: "a particular thing that will happen." But then there is a problem, not all promises are fulfilled.
So basically when we make a promise there are two possibilities -- either the promise is fulfilled or not.
The promise in
JavaScript is used to represent any operation that is deferred or is expected to be completed in the future, as an asynchronous ajax request. The syntax goes as given below,
- var objPromise = new Promise(function (fulfilled, reject) {
-
- });
The function passed a parameter to the Promise function known as the executor. The executor function has two parameters which are other callback functions.
As discussed above a promise may have two possible outputs
- Either the Promise is Fulfilled or
- Promise is not Fulfilled i.e rejected
So a promise is in one of these states
- pending (the operation is pending)
- fulfilled (the operation is completed successfully)
- rejected (the operation failed)
If the operation is completed successfully then the fulfilled function is to be called or the rejected function is to be called.
Example
- var objPromise = new Promise(function (fulfilled, reject) {
- $.ajax({
- url: "/JSON/states.json",
- success: function(result){
- fulfilled(result);
- }
- error: function(error){
- reject(error);
- }
- });
- });
The above-made promise makes an ajax call to retrieve a list of states from a JSON file, now either the ajax request will retrieve the list of states or it will fail to do the same. If successful the fulfilled method is called and the result is passed to it as a parameter and in case of any error the reject function is called and the object of error is passed to the reject function.
Now that we have created the promise, we can use it by using the method "then" and "catch" which will return the promise.
Example
- objPromise().then(function(data) {
-
- })
- .catch(function(error){
-
- });
-
-
- objPromise().then(function(data) {
-
- }, function(error){
-
- });
Now that you know what Promises are, you may practically think that why should one use a promise as it is just another callback function.
So to recognize the need for the promise, let's consider a scenario where we want to bind two dropdowns; one with a list of states and another list of its corresponding city.
So the traditional way of doing this would be...
- $(document).ready(function () {
-
- $.get('/JSON/state.json', function (data) {
- $('#ddlState').itemTemplate({
- dataSource: data
- });
- });
-
- $('#ddlState').change(function () {
- $.get('/JSON/city.json', function (data) {
- var filteredData = [];
- filteredData = filterCityByState(data);
- $('#ddlCity').itemTemplate({
- dataSource: filteredData
- });
- });
- });
- });
-
-
- function filterCityByState(data) {
- var filteredData = [];
- $.each(data, function (index, item) {
- if (item.stateId == $('#ddlState').val()) {
- filteredData.push(item);
- }
- });
- return filteredData;
- }
Now to increase the significance of this example I have introduced a latency of three seconds to the filter function called filterCityByState,
- function filterCityByState(data) {
- var filteredData = [];
- setTimeout(function () {
- $.each(data, function (index, item) {
- if (item.stateId == $('#ddlState').val()) {
- filteredData.push(item);
- }
- });
- }, 3000);
- return filteredData;
- }
Now if you go and debug the code, you will find that the function inside the setTimeout is executed three seconds after all the code is executed outside the setTimeout function. So basically the setTimeout function deferred/delayed the execution of the code inside it which filtered the data, hence returning a blank array.
So to overcome this problem one can remove the setTimeout function or use a promise instead.
- function getJsonData(url) {
-
-
- return new Promise(function (fullfilled, reject) {
- $.get(url, function (data) {
-
- fullfilled(data);
- }).fail(function (error) {
-
- reject(error);
- });
- });
- }
- function filterCityByState(data) {
-
-
- return new Promise(function (fullfilled, reject) {
- setTimeout(function () {
- var filteredData = [];
- $.each(data, function (index, item) {
- if (item.stateId == $('#ddlState').val()) {
- filteredData.push(item);
- }
- });
-
- fullfilled(filteredData);
- }, 3000);
- })
- }
-
- $(document).ready(function () {
- getJsonData('/JSON/state.json').then(function (data) {
- $('#ddlState').itemTemplate({ dataSource: data });
- });
- $('#ddlState').change(function () {
-
-
-
-
-
-
-
- getJsonData('/JSON/city.json')
- .then(function (data) { return filterCityByState(data) }).catch(function (error) { alert('Error Occured'); })
- .then(function (filetereddata) { $('#ddlCity').itemTemplate({ dataSource: filetereddata }); });
- });
- });
So basically a Promise is like an event which is fired in response to fulfillment or rejection of a deferred function.
That's all for now.
Please do not forget to provide your valuable suggestions and feel free to ask queries.
That's all for this article, will see you in some other article. Until then,
Keep Learning...
Read more articles on JavaScript