map 같은 루프문을 이용하여 Promise.allSettled를 사용하여 Promise 결과값들을 받게 되었을때 상태가 fulfilled 일때와 rejected일때의 결과값을 가공해야될 경우가 있다. 해당 결과값을 특정 repository에 저장 하거나 할때 각각의 Promise의 결과값에 해당하는 프로퍼티들을 추가 하여 리턴 해주어야 한다.
// es2020.promise.d.ts
interface PromiseFulfilledResult<T> {
status: "fulfilled";
value: T;
}
interface PromiseRejectedResult {
status: "rejected";
reason: any;
}
type PromiseSettledResult<T> = PromiseFulfilledResult<T> | PromiseRejectedResult;
PromiseSettled는 해당 리턴 타입을 가지고 status가 "fulfilled" 일경우에는 value값을 리턴 "rejected"일경우에는 reason을 리턴 해준다. 해당 결과 Promise 튜플들을 받아서 성공한것과 실패한것들의 데이터를 가공해야 될 경우가 자주 있다.
const sendResult = await Promise.allSettled(
return invitedEmails.map(async (email) => {
const subject = `${group.groupName} 그룹에 그룹 가입 초대를 받았습니다`;
const htmlContent = `${htmlContent}`;
}),
);
해당 이메일을 보냈을때 메일 전송과 실패에 대한 로그 테이블에 결과들을 저장 할때 다음과 같은 필드들이 필요할때
'email', 'subject' 그렇다면 각각의 Promise 객체의 결과값에 각각의 프로퍼티들을 추가하여 Promise 결과를 리턴 해주어야한다.
하지만 실패 했을때도 email과 subject프로퍼티가 필요하다.
private async sendEmail(
email: string,
subject: string,
text: string,
htmlContent: string,
) {
const result = await this.mailerService
.sendMail({
to: email,
subject,
text: text,
html: htmlContent,
})
.catch((err) => {
throw {
reason: err,
toEmail: email,
subject,
};
});
return {
value: result,
toEmail: email,
subject,
};
}
이런식으로 value값에 기존 return을 담아주고 reason에 기존 reason인 err를 담아준다. 그리고 추가 프로퍼티인 toEmail과 subject를 추가 해준다.
// 변경전 결과값
[
{
status: 'rejected',
reason: Error: Invalid login: 535-5.7.8 Username and Password not accepted. For more information, go to
) {
code: 'EAUTH',
response: 'response',
responseCode: 535,
command: 'AUTH PLAIN'
}
}
]
// 변경 후 결과값
[
{
status: 'rejected',
reason: {
reson: [Error],
toEmail: '123',
subject: '양씨네가족 그룹에 그룹 가입 초대를 받았습니다'
}
},
{
status: 'rejected',
reason: {
reson: [Error],
toEmail: '123',
subject: '양씨네가족 그룹에 그룹 가입 초대를 받았습니다'
}
}
]