JavaScript | Promises
JavaScript promises are object which used for holding value of Async operation. The value can be either success and failure.
You can refer below links to learn more about promises.
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
- https://javascript.info/promise-basics
In earlier post I'd mentioned about callbacks. Adding multiple callbacks in code make code more complicated and not readable. We can solve this issue with callbacks.
The $.get used already returns promise object so we can directly call then() method of promise object to do processing. We returned the call to second rest so that its result will be available in chain format.
This is useful where we have to call one rest one after another. The fail() at last of chain can be added to catch any errors.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getResponseFromRestAPI() { | |
$.get("https://jsonplaceholder.typicode.com/posts/1") | |
.then(function(responseOfFirstRest){ | |
//do processing | |
$('#p1').text('Get response received from 1st rest' + JSON.stringify(responseOfFirstRest)); | |
//We call 2nd rest API and return it as it also return promise object. Which we can use in then() chain object. | |
return $.get("https://jsonplaceholder.typicode.com/posts/2"); | |
}) | |
.then(function(responseOfSecondRest){ | |
//do processing | |
$('#p2').text('Get response received from 2nd rest' + JSON.stringify(responseOfSecondRest)); | |
}); | |
} | |
getResponseFromRestAPI(); |
Comments
Post a Comment