Promise / async-await
function
ES6
Promises represent eventual completion of async operations. async/await is syntactic sugar over Promises.
Syntax
async function fn() { const result = await promise; }
Example
javascript
// Promise
fetch('https://api.example.com/users')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// async/await (cleaner)
async function getUsers() {
try {
const res = await fetch('https://api.example.com/users');
const data = await res.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
// Parallel requests
const [users, posts] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
]);