如何在原生ES6 Promises中使用TypeScript?


在ECMAScript的ES6版本中,首次引入了Promise。

要在TypeScript專案中使用ES6 promises,使用者需要修改tsconfig.json檔案。

在“compilerOptions”物件中新增以下程式碼。

{
   "compilerOptions": {
      "target": "es6",
   }
}

此外,使用者也可以在“lib”屬性中新增“ES6”,如下所示。

{
   "compilerOptions": {
      "lib": [
         "es6",
         "dom"
      ],
   }
}

但是,使用者也可以使用更高版本的ECMAScript,因為它們支援TypeScript中的原生promises。例如,es7、es10等。

TypeScript中的原生promises是指在TypeScript程式碼中由Promise()建構函式建立的promises。但是,我們可以解析從任何API請求返回的promises。

promises可以具有以下三種狀態。

  • 等待中 – 表示promise尚未完成。

  • 已完成 – 表示promise已成功完成,沒有任何錯誤。

  • 已拒絕 – 表示promise已完成並出現錯誤。

語法

使用者可以按照以下語法在TypeScript中使用原生promises。

const promise = new Promise((resolve, reject) => {
   
   // resolve or reject the promise
});
promise
.then(() => {
   
   // show results
})
.catch(() => {
   
   // show error
});

在上述語法中,我們使用Promise()建構函式建立了promise,並在then()和catch()塊中分別處理了結果和錯誤。“T”表示promise成功完成時的返回型別。

示例1(基本Promises)

在下面的示例中,我們將學習在TypeScript中使用ES6原生promises的基本方法。我們建立了兩個名為first_promise和second_promise的promises。我們已完成first_promise並拒絕了second_promise。

此外,使用者可以看到promises的返回型別是字串。由於first_promise成功完成,執行控制轉到then()塊;由於second_promise被拒絕,執行控制轉到catch()塊。

// resolving a promise
const first_promise = new Promise((res, rej) => {
   res("First promise resolved");
});
first_promise
.then((result: string) => {
   console.log(result);
})
.catch((err) => {
   console.log(err);
});

// rejecting a promise
const second_promise = new Promise((res, rej) => {
   rej("Second promise rejected");
});
second_promise
.then((result: string) => {
   console.log(result);
})
.catch((err) => {
   console.log(err);
});

編譯後,它將生成以下JavaScript程式碼。

// resolving a promise
var first_promise = new Promise(function (res, rej) {
   res("First promise resolved");
});
first_promise
.then(function (result) {
   console.log(result);
})["catch"](function (err) { 
   console.log(err);
});

// rejecting a promise
var second_promise = new Promise(function (res, rej) {
   rej("Second promise rejected");
});
second_promise
.then(function (result) {
   console.log(result);
})["catch"](function (err) {
   console.log(err);
});

示例2(巢狀Promises)

在下面的示例中,我們演示瞭如何使用巢狀promises。我們使用new關鍵字和Promise()建構函式建立了outer_promise。在outer_promise的回撥函式中,我們建立了新的子promise並完成了子promise。

在輸出中,使用者可以看到outer_promise作為子promise成功完成。如果我們拒絕子promise,outer_promise也會被拒絕。

// resolving a promise
const outer_promise = new Promise((res) => {
   res(
      new Promise((resChild) => {
         resChild("Child Promise Resolved");
      })
   );
});
outer_promise
.then((result: string) => {
      console.log(result);
})
.catch((err) => {
   console.log(err);
}); 

編譯後,它將生成以下JavaScript程式碼。

// resolving a promise
var outer_promise = new Promise(function (res) {
   res(new Promise(function (resChild) {
      resChild("Child Promise Resolved");
   }));
});
outer_promise
.then(function (result) {
   console.log(result);
})["catch"](function (err) {
   console.log(err);
});

示例3(鏈式Promises)

在下面的示例中,我們演示了TypeScript中的鏈式promise。顧名思義,它是一系列promises。在這裡,我們完成numeric_promise時返回數值。

我們在then()塊中收到結果10。之後,我們將結果乘以2並返回。我們可以在第二個then()塊中從第一個then()塊中獲取返回值,依此類推。如果發生任何錯誤,控制會直接轉到catch()塊。

在輸出中,使用者可以看到結果值在每個then()塊中都加倍。

// resolving a promise
const numeric_promise = new Promise((res) => {
   res(10);
});
numeric_promise
.then((result: number) => {
   console.log("The result in the first then() block is - " + result);
   return result * 2;
})
.then((result: number) => {
   console.log("The result in the second then() block is - " + result);
   return result * 2;
})
.then((result: number) => {
   console.log("The result in the third then() block is - " + result);
   return result * 2;
})
.then((result: number) => {
   console.log("The result in the fourth then() block is - " + result);
})
.catch((err) => {
   console.log(err);
}); 

編譯後,它將生成以下JavaScript程式碼。解決promise

var numeric_promise = new Promise(function (res) {
   res(10);
});
numeric_promise
.then(function (result) {
   console.log("The result in the first then() block is - " + result);
   return result * 2;
})
.then(function (result) {
   console.log("The result in the second then() block is - " + result);
   return result * 2;
})
.then(function (result) {
   console.log("The result in the third then() block is - " + result);
   return result * 2;
})
.then(function (result) {
   console.log("The result in the fourth then() block is - " + result);
})["catch"](function (err) {
   console.log(err);
}); 

使用者學習瞭如何在TypeScript中使用ES6原生promises。我們還學習瞭如何使用巢狀promises和promise鏈。通常,使用者會將promises作為API的響應,他們需要使用then()和catch()塊來解決它們。

更新於:2023年3月6日

2K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.