Advertisement
karlakmkj

async GET Request

Dec 31st, 2020
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const getData = async () => {  //async keyword will ensure that the function returns a promise.
  2.   try{
  3.     const response = await fetch('https://api-to-call.com/endpoint');
  4.     if (response.ok) {
  5.       const jsonResponse = await response.json();  //Since .json() is an asynchronous method we have to await until the promise status is resolved. Then we store the value to know what data the JSON holds.
  6.       return jsonResponse;
  7.   }
  8.    throw new Error('Request failed!');
  9.   }catch(error) {
  10.     console.log(error);
  11.   }
  12. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement