sync
Cara Kerja & Perbandingan
history
Promise (Cara Lama)
fetchData()
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
sync
Async/Await (Cara Baru)
const fetchData = async () => {
try {
const response = await fetch('/api/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
try {
const response = await fetch('/api/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
Lebih mudah dibaca - Sintaks mirip kode synchronous
Error handling sederhana - Menggunakan try/catch seperti kode biasa
code
Contoh Praktis
// Multiple API calls
const getUserData = async (userId) => {
// Ambil data user
const user = await fetch(`/api/users/${userId}`);
const userData = await user.json();
// Ambil data postingan user
const posts = await fetch(`/api/users/${userId}/posts`);
const postsData = await posts.json();
// Parallel requests
const [followers, following] = await Promise.all([
fetch(`/api/users/${userId}/followers`),
fetch(`/api/users/${userId}/following`)
]);
return {
user: userData,
posts: postsData,
followers: await followers.json(),
following: await following.json()
};
};
const getUserData = async (userId) => {
// Ambil data user
const user = await fetch(`/api/users/${userId}`);
const userData = await user.json();
// Ambil data postingan user
const posts = await fetch(`/api/users/${userId}/posts`);
const postsData = await posts.json();
// Parallel requests
const [followers, following] = await Promise.all([
fetch(`/api/users/${userId}/followers`),
fetch(`/api/users/${userId}/following`)
]);
return {
user: userData,
posts: postsData,
followers: await followers.json(),
following: await following.json()
};
};
Output:
{user: {...}, posts: [...], followers: [...], following: [...]}
{user: {...}, posts: [...], followers: [...], following: [...]}
lightbulb
Async/Await membuat kode asynchronous terasa seperti synchronous dengan error handling yang lebih intuitif