if 语句失败时重新运行函数

我想在我的 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
});

相关文章