DEV Community

AKSH DESAI
AKSH DESAI

Posted on

 

Part 2:- Try Catch javascript Syntax

Javascript Code

let btn = document.getElementById("btn");
let divdata = document.getElementById("divdata");

//Working with Json file
function makeRequest() {
    fetch('data.json')
        .then(async (res) => {
            if (!res.ok) {
                throw new Error(res.statusText)
            }
            console.log('res', res);
            const dt = await res.json()
            console.log('res.json()', await res.json());
            return dt;
        })
        .then((data) => {
            console.log(data);
            // divdata.innerHTML = data;
        })
}

//Showing Data into Browser
function makeRequest() {
    fetch('data.json')
        .then((res) => {
            if (!res.ok) {
                throw new Error(res.statusText)
            }
            return res.json();
        })
        .then((data) => {
            console.log(data);
            divdata.innerText = data.name;
            divdata.innerText += data.id;
        })
}

// Async & Await 
async function makeRequest() {
    try {
        const res = await fetch('data1.json');
        if (!res.ok){
            throw new Error("sab moh maya hai");
        }
        const data = await res.json()
        console.log(data);
        divdata.innerHTML = data.name;
    } catch (error) {
        console.log('error', error);
    }
}



btn.addEventListener('click', makeRequest); 
Enter fullscreen mode Exit fullscreen mode

Thank You.
You can follow us on:
Youtube
Instagram

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post