Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created April 11, 2020 01:15
Show Gist options
  • Save tomhodgins/a902a056199187566eb805f9f481c59b to your computer and use it in GitHub Desktop.
Save tomhodgins/a902a056199187566eb805f9f481c59b to your computer and use it in GitHub Desktop.
A variety of ways to express asynchronous stuff in JS
// In an async IIFE with await
(async () => {
const response = await fetch('http://api.open-notify.org/astros.json')
const json = await response.json()
console.log(json)
})();
// Using .then()
fetch('http://api.open-notify.org/astros.json')
.then(response => response.json())
.then(json => console.log(json));
// As an async function with await
async function fetchJSON(url = '') {
const response = await fetch(url)
const json = await response.json()
return json
};
// Using the function inside an async IIFE with await
(async () => {
console.log(await fetchJSON('http://api.open-notify.org/astros.json'))
})();
// Using the function inside an async named function, that is called
async function main() {
console.log(await fetchJSON('http://api.open-notify.org/astros.json'))
};
main();
// Top level await (works in Chrome, Edge, Firefox, …not yet Safari)
const response = await fetch('http://api.open-notify.org/astros.json');
const json = await response.json();
console.log(json);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment