How To Use JavaScript Promises and Fetch API

How To Use Javascript Promises and Fetch API

JavaScript is an interpreted language where codes are executed line by line. But the execution will not wait for the dependent codes to be executed before you execute 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.

Promises are JavaScript objects that represent an eventual completion or failure of an asynchronous operation. Promises either resolved or rejected. That means it will either return success on resolve or error on rejection.

In case of multiple asynchronous operations it provides chaining of Promises to handle that. So the code here is understandable and managed. Here is some example of callbacks and promises for your understanding

Contents

Callbacks

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);

Promises:

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);

});

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

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);

});

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.

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.

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);

});

I hope the above things help you to use JavaScript Promises and Fetch API. For more information you can check Google developers. You can also take the assistance of Andolasoft JavaScript developers. Let’s discuss.

Summary
How To Use JavaScript Promises and Fetch API
Article Name
How To Use JavaScript Promises and Fetch API
Description
JavaScript is an interpreted language where codes are executed line by line. Promises are JavaScript objects that represent an eventual completion.
Author
Publisher Name
Andolasoft

Your recently viewed posts:

    Contact Us

    We’d love to help & work with you




    When do you want to start ?


    Enter your email address to stay up to date with the latest news.
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box