if语句失败时重新运行功能 [英] Re-running function when if-statement fails

查看:59
本文介绍了if语句失败时重新运行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Discord机器人中使用reddit(reddit.com/r/SUBREDDIT/random/.json)中的随机api(使用discord.js).直到帖子不包含有效的链接之前,获取图像都可以正常工作,但是我希望它与其他与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语句失败时重新运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆