Advertisement
karlakmkj

fetch() GET request

Dec 31st, 2020
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fetch('https://api-to-call.com/endpoint')  //first argument determines the endpoint of the request.
  2. .then(response => {  //.then() will fire only after the promise status of fetch() has been resolved.
  3.   if (response.ok){
  4.     return response.json();   //Testing the ok property of the response object that it will be a Boolean value. If there were no errors, response.ok will be true and the code will return  
  5.   }
  6.   throw new Error('Request failed!');  //code will throw this error when response.ok is falsy.
  7. }, networkError => {
  8.   console.log(networkError.message);   //If we could not reach the endpoint at all, e.g., the server is down, then we would get this networkError.
  9. }).then(jsonResponse => {  //The second .then()‘s success callback won’t run until the previous .then() method has finished running. It will also not run if there was an error was thrown previously.
  10.   return jsonResponse;
  11. }
  12. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement