תכנות אסינכרוני - Async/Await
Async/Await הוא תחביר מובנה לניהול תכנות אסינכרוני ב-JavaScript שמקל על הקריאה והכתיבה של קוד אסינכרוני.
פונקציות Async
async function fetchData() {
return 'Data fetched';
}
fetchData().then(function(result) {
console.log(result); // מדפיס 'Data fetched'
});
פונקציה המסומנת כ-async
מחזירה Promise.
שימוש ב-Await
async function fetchData() {
let data = await new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Data fetched after 2 seconds');
}, 2000);
});
console.log(data);
}
fetchData();
התחביר await
עוצר את ביצוע הפונקציה עד שה-Promise שמימין לו מתמלא.
טיפול בשגיאות עם Async/Await
async function fetchData() {
try {
let data = await new Promise(function(resolve, reject) {
setTimeout(function() {
reject('Fetching data failed');
}, 2000);
});
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
ניתן להשתמש ב-try/catch
בתוך פונקציות async
כדי לטפל בשגיאות.