javascript fetch mehtod 1

javascript fetch mehtod

//feth method 

// - take the url as parameter
// - return a promise
// - pass response when resolved
// - pass error when rejected
// - the response has the http response information
// - use the .json() is used to get the body of the response
// - .json return a promise
// - resolve the promise with data as the argument

        fetch("test.json")
            .then(response =>{
                return response.json();
            }).then(data=>{
                document.body.innerHTML = data.name;
                console.log(data)
            }).catch(error =>{
                console.error(error)
            })

Here is what the above code is Doing:
1. fetch() takes the path to the resource as a parameter
2. fetch() returns a promise
3. The promise is resolved with the response object
4. The response object has the http response information
5. The .json() method is used to get the body of the response
6. .json() returns a promise
7. The promise is resolved with the data as the argument
8. The data is then used to update the DOM
9. The catch() method is used to catch any errors

Similar Posts