Lớp Promise trong TypeScript
Bài viết này giải thích lớp Promise trong TypeScript.
YouTube Video
Promise
Lớp Promise
trong TypeScript về cơ bản giống như Promise
trong JavaScript. Promise
là một lớp tích hợp sẵn để xử lý các thao tác bất đồng bộ, đại diện cho kết quả của một thao tác bất đồng bộ khi nó hoàn thành. Ở đây, chúng tôi giải thích cách sử dụng cơ bản của Promise và các khái niệm liên quan.
Cách sử dụng cơ bản
Tạo một Promise:
Đối tượng Promise
được sử dụng để bao bọc các thao tác bất đồng bộ. Promise
được tạo bằng new Promise(executor)
và thực thi các thao tác bất đồng bộ bên trong nó. Hàm executor
nhận hai hàm, resolve
và reject
, làm đối số.
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});
Sử dụng Promise:
Promise
được tạo ra sẽ được xử lý bằng cách sử dụng then()
và 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});
Phương thức 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});
- Phương thức
finally()
định nghĩa mã sẽ luôn được thực thi bất kểPromise
được hoàn thành hay bị từ chối.
Chuỗi Promise:
Bằng cách nối các then()
liên tiếp, bạn có thể kết nối nhiều thao tác bất đồng bộ theo chuỗi.
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:
Trong TypeScript, bạn có thể xử lý Promise dễ dàng hơn bằng cách sử dụng async
/await
. Trong một hàm async
, bạn có thể sử dụng từ khóa await
để chờ kết quả của một 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();
Các phương thức Promise
Promise.all()
Promise.all
thực thi nhiều Promise cùng lúc và đợi cho đến khi tất cả đều được hoàn thành.
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()
chỉ được gọi khi tất cả cácPromise
đều được hoàn thành.catch()
sẽ được gọi nếu có ít nhất một Promise bị lỗi.
Promise.race()
Promise.race
trả về kết quả của Promise đầu tiên hoàn thành trong số nhiều 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});
- Như trong ví dụ này, kết quả của Promise đầu tiên hoàn thành sẽ được trả về.
Promise.allSettled()
Promise.allSettled
chờ tất cả các Promise hoàn thành và trả về một mảng kết quả, bao gồm cả thành công lẫn thất bại.
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()
được gọi sau khi tất cả cácPromise
đã hoàn thành (dù là thành công hay thất bại). Mỗi kết quả đều bao gồm thuộc tínhstatus
('fulfilled'
hoặc'rejected'
). Các thất bại không ảnh hưởng đến những thao tác khác.
Promise.any()
Promise.any
sẽ chờ đến khi Promise đầu tiên được hoàn thành và trả về kết quả của nó.
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 });
- Nó trả về giá trị đầu tiên được hoàn thành trong số nhiều
Promise
.
Tóm tắt
Bằng cách sử dụng TypeScript, bạn có thể chỉ định kiểu cho các Promise một cách phù hợp, cho phép bạn viết các chương trình an toàn về kiểu hơn. Điều này giúp phát hiện lỗi sớm trong quá trình phát triển bằng cách xác định trước loại giá trị mà một Promise sẽ trả về.
Bạn có thể làm theo bài viết trên bằng cách sử dụng Visual Studio Code trên kênh YouTube của chúng tôi. Vui lòng ghé thăm kênh YouTube.