In my current setup, I have a function called emailIterator
that reads messages from a stack and sends them one by one using an emailer. The process is done recursively by calling emailIterator
with fewer messages each time as they are sent.
import { emailer } from 'pigeon';
interface MessageObject {
email: string;
recipientName: string;
message: string;
}
interface ErrorFormat {
error: any;
messageAtError: MessageObject;
}
const data: MessageObject[] = [
{
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddbfb2bf9db9b2b0bcb4b3f3beb2b0">[email protected]</a>',
recipientName: 'Bob',
message: 'Lorem ipsum dolor sit amet mattis.',
},
{
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c1615113c1813111d1512521f1311">[email protected]</a>',
recipientName: 'Jim',
message: 'Lorem ipsum dolor sit amet mattis.',
},
];
const emailIterator = (messages: MessageObject[], cb: any): void => {
if (messages.length === 0) {
return cb(undefined, 'All messages sent');
} else {
const toSend = messages.pop();
emailer(toSend)
.then(() => {
return emailIterator(messages, cb);
})
.catch((e) => {
return cb({
error: e,
messageAtError: toSend,
});
});
}
};
emailIterator(data, (err?: ErrorFormat, msg?: string) => {
if (err) {
console.log('There was an error with a message:', err.messageAtError);
console.error(err.error);
return;
}
console.log(msg);
});
I'm looking to convert this recursive solution into an iterative one. Here's my attempt so far. Does it handle errors efficiently? Can it be improved?
const emailIterator2 = async (messages: MessageObject[], cb: any): void => {
for(let i = messages.length - 1; i >= 0; i--) {
let toSend = messages[i];
try {
const result = await emailer(toSend);
} catch (e: ErrorFormat) {
return cb({
error: e,
messageAtError: toSend
})
}
if(i === 0) {
return cb(undefined, 'All messages sent')
}
}
}