fetch() await

by Gustavo

JavaScript

// Without error handling
async function getData1() {

	const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const data = await res.json();
  return data; // it will return a promise because it's an async function
  
}


// With error handling
async function getData2() {

	try {
      const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
      if (!res.ok) {
  			throw new Error(`Error: ${res.status}`);
      }
      const data = await res.json();
      return data; // it will return a promise because it's an async function
  } catch (err) {
  		throw new Error(err);
  }
  
}

const data = getData2().then((data) => { console.log(data.title) });