מחלקת הבטחה ב-TypeScript
מאמר זה מסביר את מחלקת ההבטחה ב-TypeScript.
YouTube Video
הבטחה
מחלקת ה-Promise
ב-TypeScript זהה בעיקרון למחלקת ה-Promise
ב-JavaScript. מחלקת Promise
היא מחלקה מובנית לניהול פעולות אסינכרוניות, המציגה את התוצאה של פעולה אסינכרונית כאשר היא מסתיימת. כאן נסביר את השימוש הבסיסי בהבטחות ואת המושגים הקשורים לכך.
שימוש בסיסי
יצירת הבטחה:
אובייקט Promise
משמש לעטיפת פעולות אסינכרוניות. יוצרים Promise
עם new Promise(executor)
, והוא מבצע פעולות אסינכרוניות בתוכו. ה־executor
מקבל שתי פונקציות, resolve
ו־reject
, כארגומנטים.
1const myPromise = new Promise<number>((resolve, reject) => {
2 // Perform asynchronous operations
3 const success = true; // This is just an example
4 if (success) {
5 resolve(42); // In case of success
6 } else {
7 reject('Failed'); // In case of failure
8 }
9});
שימוש בהבטחה:
מעבדים את ה-Promise
שנוצר באמצעות then()
ו-catch()
.
1myPromise.then((value) => {
2 console.log(`Success: ${value}`); // Process the value passed with resolve
3}).catch((error) => {
4 console.error(`Error: ${error}`); // Handle the error passed with reject
5});
שיטת finally()
1const myPromise = new Promise<number>((resolve, reject) => {
2 // Perform asynchronous operations
3 const success = false; // This is just an example
4 if (success) {
5 resolve(42); // In case of success
6 } else {
7 reject('Failed'); // In case of failure
8 }
9});
10
11myPromise.then((value) => {
12 console.log(`Success: ${value}`); // Process the value passed with resolve
13}).catch((error) => {
14 console.error(`Error: ${error}`); // Handle the error passed with reject
15}).finally(() => {
16 console.log('The operation has completed');
17});
- שיטת
finally()
מגדירה קוד שיתבצע תמיד, בין אם ה-Promise
קוים ובין אם נדחה.
שרשור הבטחות:
על ידי שרשור then()
אחרי then()
, ניתן לקשר מספר פעולות אסינכרוניות ברצף.
1const myPromise = new Promise<number>((resolve, reject) => {
2 // Perform asynchronous operations
3 const success = true; // This is just an example
4 if (success) {
5 resolve(42); // In case of success
6 } else {
7 reject('Failed'); // In case of failure
8 }
9});
10
11myPromise
12 .then((value) => {
13 console.log(`Success: ${value}`);
14 return value + 1; // Pass the value to the next then
15 })
16 .then((newValue) => {
17 console.log(`New value: ${newValue}`);
18 })
19 .catch((error) => {
20 console.error(`Error: ${error}`);
21 });
async/await:
ב-TypeScript, ניתן לטפל בהבטחות בצורה פשוטה יותר באמצעות async
/await
. בתוך פונקציה async
, ניתן להשתמש במילת המפתח await
כדי להמתין לתוצאת ה-Promise.
1const myPromise = new Promise<number>((resolve, reject) => {
2 // Perform asynchronous operations
3 const success = true; // This is just an example
4 if (success) {
5 resolve(42); // In case of success
6 } else {
7 reject('Failed'); // In case of failure
8 }
9});
10
11async function asyncFunction() {
12 try {
13 const value = await myPromise;
14 console.log(`Success: ${value}`);
15 } catch (error) {
16 console.error(`Error: ${error}`);
17 }
18}
19
20asyncFunction();
שיטות הבטחה
Promise.all()
Promise.all
מפעיל מספר הבטחות (Promises) במקביל וממתין עד שכולן יקויימו.
1const promise1 = Promise.resolve(1);
2const promise2 = Promise.resolve(2);
3const promise3 = Promise.resolve(3);
4
5Promise.all([promise1, promise2, promise3])
6 .then((results) => {
7 console.log(results); // [1, 2, 3]
8 })
9 .catch((error) => {
10 console.error('Error :', error);
11 });
then()
ייקרא רק כאשר כל ההבטחות (Promises) קוימו.catch()
ייקרא אם אפילו אחת נכשלת.
Promise.race()
Promise.race
מחזיר את התוצאה של ההבטחה (Promise) הראשונה שמסתיימת מבין מספר הבטחות.
1const promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'First'));
2const promise2 = new Promise((resolve) => setTimeout(resolve, 500, 'Second'));
3
4Promise.race([promise1, promise2]).then((result) => {
5 console.log(result); // "First"
6});
- כמו בדוגמה זו, מוחזרת התוצאה של ה-
Promise
הראשון שמסתיים.
Promise.allSettled()
Promise.allSettled
ממתין שכל ההבטחות יסתיימו ומחזיר מערך של כל התוצאות, כולל אלו שקוימו ואלו שנדחו.
1const promise1 = Promise.resolve(1);
2const promise2 = Promise.reject("Failed");
3const promise3 = Promise.resolve(3);
4
5Promise.allSettled([promise1, promise2, promise3])
6 .then((results) => {
7 results.forEach(result => console.log(result));
8 // [
9 // { status: 'fulfilled', value: 1 },
10 // { status: 'rejected', reason: 'Failed' },
11 // { status: 'fulfilled', value: 3 }
12 // ]
13 });
then()
ייקרא כאשר כל ההבטחות הסתיימו (בין אם קוימו ובין אם נדחו). כל תוצאה כוללת מאפייןstatus
('fulfilled'
או'rejected'
). כישלונות אינם משפיעים על שאר הפעולות.
Promise.any()
Promise.any
ממתין עד שההבטחה הראשונה תקויים ומחזיר אותה.
1const promise1 = new Promise((resolve) => setTimeout(() => resolve("A ok"), 300));
2const promise2 = new Promise((_, reject) => setTimeout(() => reject("B fail"), 100));
3const promise3 = new Promise((resolve) => setTimeout(() => resolve("C ok"), 200));
4
5Promise.any([promise1, promise2, promise3])
6 .then(value => {
7 // Logs the first fulfilled value ("C ok")
8 console.log("first fulfilled:", value);
9 })
10 .catch(err => {
11 console.log("should not reach here in this example:", err);
12 });
- הוא מחזיר את הערך הראשון שקוים מבין מספר הבטחות (Promises).
סיכום
על ידי שימוש ב-TypeScript, ניתן להגדיר את סוגי ההבטחות בצורה מדויקת, המאפשרת לכתוב תוכניות בטוחות יותר מבחינת טיפוסים. זה עוזר לזהות שגיאות מוקדם יותר במהלך הפיתוח על ידי הגדרת סוג הערך שה-Promise מחזיר מראש.
תוכלו לעקוב אחר המאמר שלמעלה באמצעות Visual Studio Code בערוץ היוטיוב שלנו. נא לבדוק גם את ערוץ היוטיוב.