TypeScript 中的 Promise 类
本文讲解了 TypeScript 中的 Promise 类。
YouTube Video
Promise
TypeScript 中的 Promise 类基本上与 JavaScript 中的 Promise 相同。Promise 是一个用于处理异步操作的内置类,表示异步操作完成后的结果。这里,我们讲解 Promise 的基本用法和相关概念。
基本用法
创建一个 Promise:
Promise 对象用于封装异步操作。通过 new Promise(executor) 创建一个 Promise,并在其中执行异步操作。“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 被解决(fulfilled)还是被拒绝(rejected)都会执行的代码。
链式调用 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 更直观地处理 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,并等到它们全部被解决(fulfilled)。
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 都被解决(fulfilled)时才会调用 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 被解决(fulfilled)后返回。
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 中返回第一个被解决(fulfilled)的值。
总结
通过使用 TypeScript,可以为 Promise 合理地指定类型,从而编写更类型安全的程序。通过预先指定 Promise 返回的值的类型,可以在开发过程中更早地捕捉到错误。
您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。