Async JavaScript
Async/Await and Fetch
async/await lets you write asynchronous code that reads like normal, top-to-bottom code. fetch loads data from a server.
async function loadUser(id) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const user = await response.json();
console.log(user.name, "-", user.email);
} catch (error) {
console.error("Could not load user:", error.message);
}
}
loadUser(1);Output
Leanne Graham - Sincere@april.biz
awaitcan only be used inside anasyncfunction (or at the top level of a module).fetchdoes not throw on 404 or 500, so always checkresponse.ok.
Sending data
await fetch("/api/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: "Hello!" }),
});