The await keyword is used inside async functions to pause execution until a Promise is resolved. It gives asynchronous code a synchronous look.
async function example() {
let result = await Promise.resolve(123);
console.log(result); // 123
}
example();
async function fetchPost() {
let res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let post = await res.json();
console.log(post.title);
}
fetchPost();
async function chain() {
let a = await Promise.resolve(1);
let b = await Promise.resolve(a + 1);
return b;
}
chain().then(console.log); // 2
async function errorDemo() {
try {
let v = await Promise.reject("Fail!");
} catch (e) {
console.log("Error:", e);
}
}
errorDemo();
await can only be used inside async functions (in modules, top-level await is allowed in modern environments).Promise.all().
async function parallel() {
let [a, b] = await Promise.all([
fetch(url1),
fetch(url2)
]);
}