I am working on a serverless function to be hosted on Netlify to subscribe users to a mailchimp email list.
I am getting the following obscure error:
lambda response was undefined. check your function code again
Here is my function:
const handler = async function (event, context) {
try {
let body = JSON.parse(event.body);
mailchimp.setConfig({
apiKey: 'XXXXXXXXX',
server: 'us20',
});
const submit = async () => {
const response = await mailchimp.lists.addListMember("XXXXXXXX", {
email_address: body.email.toLowerCase(),
status: 'subscribed'
});
if (response.errors !== undefined && response.errors.length) {
throw new Error(response.errors);
}
}
submit().then(response => {
console.log(response);
return {
statusCode: 200,
body: JSON.stringify({ response }),
}
}).catch(errors => {
return {
statusCode: 500,
body: JSON.stringify({ errors }),
}
});
} catch (error) {
// output to netlify function log
console.log(error);
return {
statusCode: 500,
// Could be a custom message or object i.e. JSON.stringify(err)
body: JSON.stringify({ msg: error.message }),
}
}
}
module.exports = { handler }
I think the issue may be because nothing is being returned after calling submit(), but I am not sure how best to return it. I still can't quite get my head around promises.
I am really hoping someone can point me in the right direction.
Many thanks David