JS async function keeps running even after I returned result. What am I doing wrong here?

308 views Asked by At

I'm trying to customize a Slack Bot with Botkit for exercise but I ran into a problem and I can't seem to figure it out. I want to retrieve a random post from Reddit, check if it's an image and then return it if it is, otherwise get another post. Now, I'm not that familiar with async/await functions, I read a few docs about it, but looks like I'm still not getting something right here. Can someone point me in the right direction?

So in my script I have this:

const reddit = require( '../app/reddit' )

module.exports = function(controller) {
    controller.hears( 'test123', 'message,direct_message', async ( bot, message ) => {
        let image = await reddit.get_random_image()
        console.log(image)
    } )
}

And also this:

const get_random_image = async () => {

    let posts = await wrap.getHot( 'memes', { limit: 100 } )

    const post = fn.get_random_array_item( posts )

    if ( post.url.indexOf('.jpg') !== -1 || post.url.indexOf('.png') !== -1 || post.url.indexOf('.gif') !== -1 ) {
        console.log('image')
        return Promise.resolve( '*' + post.title + '* ( /' + post.subreddit_name_prefixed + ' )\n' + post.url )
    } else {
        console.log('not an image')
        return await get_random_image()
    }

}
module.exports.get_random_image = get_random_image

What happens is, when I write 'test123' in Slack, the function runs and it the first post is indeed an image everything seems fine and code stops, but if first post is not an image and function calls itself again it runs over and over again for some time, even when image is encountered.

Edit:

Added screenshots of console. This happends if first selected post is not an image: This happends when first selected post is not an image

And this happends when it is an image: And this happends when it is an image

0

There are 0 answers