คลาส Promise ใน TypeScript

คลาส Promise ใน TypeScript

บทความนี้อธิบายคลาส Promise ใน TypeScript

YouTube Video

คำมั่นสัญญา (Promise)

คลาส Promise ใน TypeScript มีพื้นฐานเหมือนกับ Promise ใน JavaScript Promise เป็นคลาสในตัวที่ใช้จัดการกับการดำเนินการแบบอะซิงโครนัส โดยแสดงผลลัพธ์ของการดำเนินการอะซิงโครนัสเมื่อเสร็จสมบูรณ์ ที่นี่ เราอธิบายการใช้งานพื้นฐานของ Promise และแนวคิดที่เกี่ยวข้อง

การใช้งานพื้นฐาน

การสร้าง 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:

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 จะสำเร็จหรือถูกปฏิเสธก็ตาม

การเชื่อมต่อ 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 คุณสามารถจัดการกับ Promise ได้ง่ายขึ้นโดยใช้ 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

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() จะถูกเรียกเมื่อทุก Promise สำเร็จเท่านั้น catch() จะถูกเรียกหากมีแม้แต่ตัวเดียวที่ล้มเหลว

Promise.race()

Promise.race จะส่งคืนผลลัพธ์ของ Promise ตัวแรกที่เสร็จสิ้นในบรรดาหลาย 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 จะรอให้ทุก Promise เสร็จสิ้นและส่งกลับอาร์เรย์ของผลลัพธ์ทั้งหมด ทั้งที่สำเร็จและถูกปฏิเสธ

 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() จะถูกเรียกเมื่อ Promise ทุกตัวเสร็จสิ้น (จะสำเร็จหรือถูกปฏิเสธก็ได้) แต่ละผลลัพธ์จะมีคุณสมบัติ status ('fulfilled' หรือ 'rejected') ความล้มเหลวจะไม่ส่งผลต่อการดำเนินการอื่น

Promise.any()

Promise.any จะรอจนกว่า Promise ตัวแรกจะสำเร็จและส่งค่านั้นกลับมา

 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    });
  • มันจะส่งค่าที่สำเร็จตัวแรกในบรรดา Promise หลายตัวกลับมา

สรุป

ด้วยการใช้ TypeScript คุณสามารถระบุประเภทของ Promise ได้อย่างเหมาะสม ทำให้เขียนโปรแกรมที่มีความปลอดภัยในเชิงประเภทยิ่งขึ้น สิ่งนี้ช่วยในการจับข้อผิดพลาดในช่วงการพัฒนาได้ตั้งแต่ต้นโดยระบุประเภทของค่าที่ Promise คืนกลับล่วงหน้า

คุณสามารถติดตามบทความข้างต้นโดยใช้ Visual Studio Code บนช่อง YouTube ของเรา กรุณาตรวจสอบช่อง YouTube ด้วย

YouTube Video