Hari 10: Promise & Async/Await
70 min
Last updated 09 Apr 2026
Promise — Menangani Operasi Async
// Membuat Promise
const ambilData = new Promise((resolve, reject) => {
const berhasil = true;
setTimeout(() => {
if (berhasil) resolve({ nama: "Budi", umur: 25 });
else reject(new Error("Gagal mengambil data"));
}, 1000);
});
// Menggunakan Promise
ambilData
.then(data => console.log(data.nama)) // "Budi"
.catch(err => console.error(err.message))
.finally(() => console.log("Selesai"));
Async/Await — Lebih Bersih
async function simulasiAPI(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, nama: `User ${id}`, aktif: true });
else reject(new Error("ID tidak valid"));
}, 100);
});
}
async function main() {
try {
const user = await simulasiAPI(5);
console.log(`User: ${user.nama}`);
const [u1, u2] = await Promise.all([simulasiAPI(1), simulasiAPI(2)]);
console.log(`${u1.nama} & ${u2.nama}`);
} catch (err) {
console.error("Error:", err.message);
}
}
main();
💡
Notice: async function selalu return Promise. await menunggu Promise resolve sebelum melanjutkan eksekusi.
Assignment
Buat fungsi async tundaKemudian(nilai, detik) yang return Promise yang resolve setelah detik ms dengan nilai ganda. Tampilkan hasilnya.
Expected output:
Mulai...
Hasil: 42
Selesai!
JS
script.js
Solution
Output