TypeScript 中的 Promise 類別

TypeScript 中的 Promise 類別

本文介紹了 TypeScript 中的 Promise 類別。

YouTube Video

Promise(承諾)

TypeScript 中的 Promise 類別與 JavaScript 中的 Promise 類別基本相同。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 被解決還是被拒絕都會執行的程式碼。

串接 Promises

通過在 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 更直觀地處理 Promise。在 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 會同時執行多個 Promise,並等待所有的 Promise 都被解決後才繼續。

 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    });
  • 只有當所有的 Promise 都被解決時才會呼叫 then()。只要有一個失敗,就會呼叫 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 會等待所有 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    });
  • 所有 Promise 都完成(不論解決或拒絕)後,會呼叫 then()。每一個結果都包含一個 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 返回值的類型來及早發現錯誤。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video