Created
April 11, 2020 01:15
-
-
Save tomhodgins/a902a056199187566eb805f9f481c59b to your computer and use it in GitHub Desktop.
A variety of ways to express asynchronous stuff in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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