I am new to Node JS and trying to build a simple Slack slash command that looks up a query in a glossary in Google sheets.
I am struggling to understand how to properly handle async/await. And seem to end up with a Promise Pending or no results at all when I run response = validateImages(response);
. I need the program to wait until the images are validated before continuing, but no matter how I write it I can't seem to make the script actually wait.
What would be the correct way of calling validateImages(response)
?
My main function looks like this:
// Gets a request object from Slack
app.post('/', (req, res) => {
const query = req.body.text;
let response = [];
// Kills request if it cannot be verified
slack.verifyWebhook(req);
// Acknowledges request to Slack
slack.ack(req, res);
// Run query on google sheet and return a list of results
response = glossary.getGlossaryResult(query); //To be implemented
// Validate images in response - and delete any invalid images
response = validateImages(response);
// Format the response for slack to meet Slack's 3000ms requirement (shorturl.at/bzDY5)
response = slackBlockFormat(response);
// Reply back to Slack on req.body.response_url
slack.reply(req, response);
});
And the validateImages() looks like this:
// Checks if each of the image URLs are valid. If they are not, delete the image from the result.
const validateImages = async(results) => {
for (let i = 0; i < results.length; i++) {
try {
// Tests the url
const res = await fetch(results[i].image.contentUrl;, {method: 'HEAD'});
// If not valid, delete
if (!res.status == 200) {
delete results[i].image.contentUrl;
}
} catch (error) {
console.error(error);
}
}
//Returns the updated results array
return results;
};
After hours on hours of tutorials, rewrites, Googling, promises, resolves, and hair pulling, I got the code working using this package (https://www.npmjs.com/package/url-exist-sync), but it feels a bit like cheating, and I would love to fundamentally understand the async/await concept.
I would be very grateful to get some help with this!