Async functions make it easier to write code that works with Promises. By writing async function, you can use await inside for a more readable, synchronous-looking style.
async function getData() {
// code
}
await inside to pause until a Promise resolves.
async function fetchUser() {
let res = await fetch("https://jsonplaceholder.typicode.com/users/1");
let user = await res.json();
console.log(user.name); // "Leanne Graham"
}
fetchUser();
async function demo() {
try {
let value = await Promise.reject("Oops!");
} catch (e) {
console.log("Caught:", e);
}
}
demo();
async function add(a, b) {
return a + b;
}
add(2, 3).then(result => console.log(result)); // 5
await new Promise)then chains to async/await in your own code. Try error handling with try/catch!