Javascript

JavaScript Fetch API, Async/Await

Await is syntactic sugar for Promises and is used for avoiding the multiple promise chains. It makes asynchronous code look more like synchronous code and makes it easier for humans to understand the code. A function declared with the async keyword is called an Async Function and await function is used inside the Async function.

When using async-await, we must wrap our code inside of a function whether it’s an anonymous function or arrow function, or a normal function and we need to wrap the function with the async keyword at the beginning of the function definition and we need to make sure that we are using awake keyword before all of our different code that’s going to be asynchronous. Otherwise, it will just return the promise and not actually return the result of that promise being executed.

Async await is just like promises and in every other way, all it does is make it easier to write promises and work with promises. Even if the return value of an async function is not explicitly a promise, it will internally make it return a promise, and await makes the code wait at that point until the promise is either resolved or rejected.

To handle the errors in an asynchronous function, the try-catch block can be used. Inside the try block, we can put all the codes that could potentially fail and throw an error. Inside the catch block (which takes a parameter in our case i.e. error), can do anything to catch the error. I have used a catch block to log the error. All of the codes inside the try block are executed and if there’s any error along the way it’s going to immediately leave and call the code inside of the catch block.

Example of Promise to get the user information.

function checkUserExist(uniqueID){
    return new Promise((resolve, reject) => {
        if(uniqueID === 'SNV123') {
            resolve(`User ${uniqueID}`)
        } else {
            reject("Please provide your unique ID")
        }
    });
}

function processUserRequest(response){
    return new Promise((resolve, reject) => {
           // console.log("Processing User Request Response");
            resolve(`${response} 's Information` )
    });
}

function completeUserRequest(responseBack) {
    return new Promise((resolve, reject) => {
        //console.log("Thank you");
        resolve(`Thank you for providing ${responseBack}!` )
    });
}

checkUserExist("SNV123").then(response => {
   return processUserRequest(response)
}).then(processResponse => {
    const requestResponse = completeUserRequest(processResponse);
    return requestResponse;
}).then(response => {
        document.getElementById("demo").innerHTML = response;
    }).catch(error => {
    console.log(error);
});

 

Example of async/await to get the user information.

function checkUserExist(uniqueID){
    return new Promise((resolve, reject) => {
        if(uniqueID === 'SNV123') {
            resolve(`User ${uniqueID}`)
        } else {
            reject("Please provide your unique ID")
        }
    });
}

function processUserRequest(response){
    return new Promise((resolve, reject) => {
        // console.log("Processing User Request Response");
        resolve(`${response} 's Information` )
    });
}

function completeUserRequest(responseBack) {
    return new Promise((resolve, reject) => {
        //console.log("Thank you");
        resolve(`Thank you for providing ${responseBack}!` )
    });
}

async function userEnquiry() {
    try {
        const response = await checkUserExist('SNV123');
        const ProcessedUserRequest = await processUserRequest(response);
        const requestResponse = await completeUserRequest(ProcessedUserRequest);
        document.getElementById("demo").innerHTML = requestResponse;
    } catch(error) {
        console.log(error)
    }
}

userEnquiry();

 

Async/await functions make longer code more readable and help in getting rid of multiple .then when using promise.

 

The Fetch API

 The fetch API allows to access resources across the network. fetch() starts a request and returns a promise.

Syntax for fetch()

const response = await fetch(resource[, options]);

resource: the URL string, or a Request object

options: the configuration object with properties like method, headers, body, credentials, and more.

For making a request and fetching a resource, we can use the fetch(). Fetch takes an URL as an argument to make a request and grab the response from the same URL as a promise. The requested URL can be either an internal or external resource. When the request completes, the promise is resolved with the Response Object. If the request fails due to some reason, the promise is rejected. Once a Response is received, there are a number of methods available to define what the body content is and how it should be handled.

There are different methods offered by the Response Object:

response.json() returns a promise resolved to a JSON object

response.text() returns a promise resolved to raw text

response.formData() returns a promise resolved to FormData

response.blob() returns a promise resolved to a Blob (a file-like object of raw data)

response.arrayBuffer()() returns a promise resolved to an ArryBuffer (raw generic binary data)

For example, let’s make a request to fetch some books:

async function fetchBooks() {
    const response = await fetch('/books');
    // waits until the request completes...
    console.log(response);
}

 

Fetching JSON

The response object, returned by the await fetch (), has multiple data formats.

For example, you can extract the JSON object from a fetch response:

async function fetchPosts() {
    try{
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    //waits until the request completes...
    const posts = await response.json();
        setTimeout(() => {
            let output = '';
            posts.forEach((post,index) => { 
            output += "<li>"+post.title+"</li>";   
            });
            document.body.innerHTML = output;
        },1000)
    } catch(error) {
        console.log(error);
    }
}

In the above example, response.json() is a method on the Response object from where we can extract a JSON object from the response. The method returns a promise, so we have to wait for the JSON: await response.json().

Handling Errors
The Promise returned from fetch() doesn’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. If the API request fails, we should handle the error and display an error message.

async function fetchMovies404() {
    const response = await fetch('/notfound');
    if (!response.ok) {
		throw new Error(`HTTP error! status: ${response.status}`);
	}
	const data = await response.json();
  }

 

Views: 615

Standard