問題描述
我想在我的 Discord 機器人(使用 discord.js)中使用來自 reddit (reddit.com/r/SUBREDDIT/random/.json) 的隨機 api.獲取圖像工作正常,直到帖子不包含有效鏈接,但我希望它在一個單獨的文件中的函數中與其他與 api 相關的東西.我的 api.js
中的函數是:
I want to use the random api from reddit (reddit.com/r/SUBREDDIT/random/.json) in my Discord bot (using discord.js). Getting images works fine until the post doens't include a valid link, but I want it in a function in a seperate file with other api-related stuff. The function in my api.js
is:
module.exports.randomReddit = async function randomReddit(reddit) {
return new Promise((res, rej) => {
axios.get(`https://www.reddit.com/r/${reddit}/random/.json`)
.then(function (response) {
res(response[0].data.children[0].data);
})
.catch(function (error) {
rej(error);
})
})
}
在我的代碼中,我目前有:
In my code, I currently have:
for (let i = 0; i < 10; i++) {
randomReddit('car').then(data => {
let regex = /.(jpg|gif|png)$/;
let test = regex.test(data.url);
if (test) message.channel.send(data.url)
continue;
})
}
隨機 reddit 帖子并不總是包含有效鏈接.我想在帖子沒有有效鏈接之前再次運行該功能(randomReddit).在這種情況下,可以發送圖像.我嘗試了一些不同的方法,但它們根本不起作用..
The random reddit post doesn't always include a valid link. I would like to run the function (randomReddit) again when a post doesn't have one until a post does have a valid link. In that case, the image may be sent. I tried a few different things but they didn't work at all..
提前謝謝你.
推薦答案
使用像 承諾重試
async function randomReddit(reddit) {
return new Promise((res, rej) => {
axios.get(`https://www.reddit.com/r/${reddit}/random/.json`)
.then(function (response) {
res(response[0].data.children[0].data);
})
.catch(function (error) {
rej(error);
})
})
}
promiseRetry(function (retry) {
return randomReddit('test')
.then(data => {
let regex = /.(jpg|gif|png)$/;
let test = regex.test(data.url);
if (test) return data;
return retry();
})
}).then(function (value) {
// Do smthg
});
這篇關于if 語句失敗時重新運行函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!