Skip to content

Instantly share code, notes, and snippets.

@ifindev
Last active February 19, 2021 10:33
Show Gist options
  • Select an option

  • Save ifindev/25c67df19b1c8995045bf7f0b187ca5f to your computer and use it in GitHub Desktop.

Select an option

Save ifindev/25c67df19b1c8995045bf7f0b187ca5f to your computer and use it in GitHub Desktop.
Using Fetch API

Nice article for fetch API and how to display fetched data to DOM https://medium.com/@armando_amador/how-to-make-http-requests-using-fetch-api-and-promises-b0ca7370a444

This is also an interesting article about fetch and how to cancel fetch request in case user switch from current page which still trying to fetch data from API or database to another page. The link https://dmitripavlutin.com/javascript-fetch-async-await/

Article about Callback vs Promises vs Async Await : https://www.loginradius.com/blog/async/callback-vs-promises-vs-async-await/

let res;
async function fetchJokesJSON() {
const response = await fetch('https://api.chucknorris.io/jokes/random');
const jokes = await response.json();
return jokes;
}
fetchJokesJSON().then(jokes => {
res = jokes.value; // fetched movies
console.log(res);
});
// Fetch request to get chuckNorris api
let res;
fetch("https://api.chucknorris.io/jokes/random")
.then(response => response.json())
.then(data => res = data)
.then(() => console.log(res.value))
// Fetch request to get data from the json placeholder
let res;
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => res = data)
.then(() => console.log(res))
tryFetch = fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {
const name = users.map(user => user.name).join("\n");
console.log(name);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment