Created
March 20, 2022 19:19
-
-
Save kieranbarker/90d3249d4723acd7a7ab11e7bff39dc4 to your computer and use it in GitHub Desktop.
A simple demo of the top-level await keyword in vanilla JS.
This file contains 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Users</title> | |
</head> | |
<body> | |
<h1>Users</h1> | |
<p>Check the JavaScript console.</p> | |
<script src="index.js" type="module"></script> | |
</body> | |
</html> |
This file contains 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
import users from "./users.js"; | |
if (users instanceof Error) { | |
console.error(users); | |
} else { | |
console.log(users); | |
} |
This file contains 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
const API = "https://jsonplaceholder.typicode.com/users"; | |
let users; | |
async function getJSON(response) { | |
if (response.ok) { | |
const data = await response.json(); | |
return Promise.resolve(data); | |
} | |
const { status, statusText } = response; | |
const error = new Error(`${status} ${statusText}`); | |
return Promise.reject(error); | |
} | |
try { | |
const response = await fetch(API); | |
users = await getJSON(response); | |
} catch (error) { | |
users = error; | |
} | |
export default users; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because of security features that web browsers implement, JavaScript modules generally don’t work with the
file://
protocol. You’ll therefore need to run a local web server on your computer.Here’s a list of one-liners for starting a local web server.