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
가 이행(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를 동시에 실행하고, 모두 이행될 때까지 기다립니다.
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()
은 모든Promise
가 이행되었을 때만 호출됩니다.catch()
는 하나라도 실패하면 호출됩니다.
Promise.race()
Promise.race
는 여러 Promise 중 가장 먼저 완료된 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가 반환하는 값의 타입을 미리 지정함으로써 개발 중에 발생할 수 있는 오류를 조기에 잡을 수 있습니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.