I am trying to display data in my template that is returned from an api fetch. I’m using Node with Fastify.
The code I am using to send to the handlebars helper from my template is:
value="{{fetchClass this.CERTIFICATION}}"
I then send this to my helper:
Handlebars.registerHelper('fetchClass', async function(str) {
try {
const response = await fetchClassification(str);
console.log('Response: ', response);
return response;
} catch (error) {
console.error('Error fetching classification:', error);
}
});
Which in turns sends to:
async function fetchClassification(parameter) {
fetch(`https://api.example.com/dictionary/CERTIFICATION/${parameter}`)
.then(response => response.json())
.then(data => {
const classification = data.meaning.classification;
return classification;
})
.catch(error => console.error('Error fetching data:', error));
}
I can console log the results and it is correct (“Standard”) but the helper returns:
Response: Promise { undefined }
I also tried doing the fetch inside my helper like:
Handlebars.registerHelper('fetchClass', function(str) {
fetch(`https://api.example.com/dictionary/CERTIFICATION/${str}`)
.then(response => response.json())
.then(data => {
const classification = data.meaning.classification;
console.log('Class: ', classification);
if (classification) {
return classification;
}
})
.catch(error => console.error('Error fetching data:', error));
});
While the console log shows correctly (Class: Standard), it doesn’t get displayed in my template.. ugh
What am I doing wrong?