Warm tip: This article is reproduced from serverfault.com, please click

Re-running function when if-statement fails

发布于 2021-01-20 11:27:06

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;

            })

        }

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..

Thank you in advance.

Questioner
Exstare
Viewed
0
Léo Martin 2021-01-20 19:32:41

What about using a library like promise-retry

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
});