Kelas Promise dalam TypeScript
Artikel ini menerangkan kelas Promise dalam TypeScript.
YouTube Video
Promise
Kelas Promise
dalam TypeScript secara asasnya adalah sama dengan Promise
dalam JavaScript. Promise
adalah kelas terbina dalam untuk mengendalikan operasi tidak segerak, mewakili hasil operasi tidak segerak apabila selesai. Di sini, kami menjelaskan penggunaan asas Promise dan konsep yang berkaitan.
Penggunaan Asas
Mencipta Promise:
Objek Promise
digunakan untuk membungkus operasi tidak segerak. Promise
dicipta dengan new Promise(executor)
, dan ia melaksanakan operasi tidak segerak di dalamnya. ‘executor’ menerima dua fungsi, ‘resolve’ dan ‘reject’, sebagai argumen.
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});
Menggunakan Promise:
Promise
yang dicipta diproses menggunakan then()
dan 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()
kaedah
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});
- Kaedah
finally()
mentakrifkan kod yang akan sentiasa dijalankan tanpa mengira sama adaPromise
dipenuhi atau ditolak.
Penggandengan Promise:
Dengan menggandengkan then()
selepas then()
, anda boleh menghubungkan pelbagai operasi tidak segerak secara bersiri.
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:
Dalam TypeScript, anda boleh mengendalikan Promise dengan lebih mudah menggunakan async
/await
. Dalam fungsi async
, anda boleh menggunakan kata kunci await
untuk menunggu hasil daripada 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();
Kaedah Promise
Promise.all()
Promise.all
melaksanakan beberapa Promise secara serentak dan menunggu sehingga kesemuanya dipenuhi.
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()
hanya akan dipanggil apabila semuaPromise
dipenuhi.catch()
akan dipanggil sekiranya walaupun satu gagal.
Promise.race()
Promise.race
mengembalikan hasil daripada Promise
pertama yang selesai di antara beberapa 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});
- Seperti dalam contoh ini, hasil dari
Promise
pertama yang selesai akan dikembalikan.
Promise.allSettled()
Promise.allSettled
menunggu sehingga semua Promise selesai dan mengembalikan satu tatasusunan semua hasil, termasuk yang dipenuhi dan ditolak.
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()
akan dipanggil selepas semuaPromise
selesai (sama ada dipenuhi atau ditolak). Setiap hasil mengandungi sifatstatus
('fulfilled'
atau'rejected'
). Kegagalan tidak menjejaskan operasi lain.
Promise.any()
Promise.any
menunggu sehingga Promise pertama dipenuhi dan mengembalikannya.
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 });
- Ia mengembalikan nilai pertama yang dipenuhi di antara beberapa
Promise
.
Ringkasan
Dengan menggunakan TypeScript, anda boleh menentukan jenis Promise dengan sewajarnya, membolehkan anda menulis program yang lebih selamat dari segi jenis. Ini membantu dalam mengenal pasti ralat lebih awal semasa pembangunan dengan menentukan jenis nilai yang Promise kembalikan terlebih dahulu.
Anda boleh mengikuti artikel di atas menggunakan Visual Studio Code di saluran YouTube kami. Sila lihat juga saluran YouTube kami.