As an interpreted language, JavaScript executes code line by line. However, it does not wait for the dependent code to execute before executing the next line.
To achieve this feature JavaScript introduces the callback function. Basically this is associated with the asynchronous operations in JavaScript.
But the issue with the callback function is if we have more than one asynchronous operation running at the same time. So it became hell to manage the code using the callback functions.
The problems are
- Hard to understand the codes because the code becomes lengthier and nested structure.
- Hard to manage the codes, because it is not clear which callbacks are called when and also there are so many callbacks to write to perform a particular task.
- Also need not satisfy all the requirements
Here JavaScript introduces the concept of Promises.
JavaScript promises represent the eventual completion or failure of asynchronous operations. Promises are either resolved or rejected. Hence, when it resolves or rejects multiple asynchronous operations, it returns either success or an error.
Never miss an update from us. Join 10,000+ marketers and leaders.
Chaining Promises is provided to handle multiple asynchronous operations. So the code here is manageable and easy to understand. For your understanding, here are some examples of callbacks and promises.
Callbacks
[code language=”css”]
function validateMoney(money){
var interest = 100;
if(money){
return money+interest;
}else{
return money;
}
}
function getInterestMoney(money, callback) {
if (typeof money !== ‘number’) {
return callback(‘money is not a number’);
} else {
return callback(money)
}
}
const money = getInterestMoney(1200, validateMoney);
console.log(money);
[/code]
Promises:
[code language=”css”]
function getInterestMoney(money) {
return new Promise((resolve, reject) => {
if (typeof money !== ‘number’) {
reject(new Error(‘money is not a number’))
} else {
var interest = 100;
money = money+interest;
resolve(money);
}
})
}
getInterestMoney(1200)
.then((money) => {
console.log(money);
}).catch((error) => {
console.error(error);
});
[/code]
Fetch API:
Fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.
Here is an example of the fetch api
[code language=”css”]
fetch(‘./api/some.json’)
.then(
function(response) {
if (response.status !== 200) {
console.log(‘Looks like there was a problem. Status Code: ‘ +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
[/code]
Chaining Promises
One of the great features of promises is the ability to chain them together. For fetch, this allows you to share logic across fetch requests.
Are you looking for a JavaScript developer
If you are working with a JSON API, you’ll need to check the status and parse the JSON for each response. You can simplify your code by defining the status and JSON parsing in separate functions which return promises, freeing you to only worry about handling the final data and the error case.
[code language=”css”]
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
fetch(‘users.json’)
.then(status)
.then(json)
.then(function(data) {
console.log(‘Request succeeded with JSON response’, data);
}).catch(function(error) {
console.log(‘Request failed’, error);
});
[/code]
Hope the aforementioned guidelines will assist you in effectively utilizing JavaScript Promises and the Fetch API. For further insights and detailed information, recommend referring to the resources available on Google Developers.
If you require expert assistance with JavaScript development, you may consider engaging the services of Andolasoft’s experienced JavaScript developers