我是Node JS的新手,正在尝试构建一个简单的Slack斜杠命令,该命令在Google表格的词汇表中查找查询。
我正在努力了解如何正确处理异步/等待。当我运行response = validateImages(response);
时,结果似乎是Promise Pending或根本没有结果。我需要程序等待图像经过验证之后才能继续,但是无论我怎么写,我似乎都无法使脚本真正等待。
调用validateImages(response)
的正确方法是什么?
我的主要功能如下:
// 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);
});
,validateImages()如下所示:
// 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;
};
经过数小时的教程,重写,谷歌搜索,承诺,解决和拔头发,我得到了使用此软件包(https://www.npmjs.com/package/url-exist-sync)进行工作的代码,但是感觉有点像作弊,我很乐意从根本上理解异步/等待的概念。
我将非常感谢能为此提供帮助!