Promise đại diện cho kết quả hoàn thành (thành công/thất bại) của tác vụ bất đồng bộ. async/await làm việc trên Promise, giúp viết code **trông đồng bộ** nhưng chạy async.
Ví dụ: Promise trả về 100 sau 2 giây
function getHundred() {
return new Promise(resolve => {
setTimeout(() => resolve(100), 2000);
});
}
Cách cũ: Callback / .then()
function useGetHundred() {
getHundred().then(value => console.log(value));
}
Cách mới: async/await
async function useGetHundredAsync() {
let value = await getHundred(); // đợi promise resolve
console.log(value); // 100
}
Đặc điểm quan trọng
async functionluôn trả về Promise.awaitchỉ dùng trongasyncfunction.- Code đọc như tuần tự, dễ debug, try/catch bắt lỗi tự nhiên.
- Parallel: dùng
Promise.all([await p1, await p2])hoặcPromise.all([p1, p2])rồi await.