Code makes an endless loop and crashes replit

How do i stop my code from overloading the RAM and cpu of my repl?

Current behavior:
What I think is happening is that the snippet puts the code in an endless loop and crashes the repl but I don’t know why/how this could happen.

Desired behavior
I want the snippet to not loop around infinitely.

Repl link:

if (interaction.commandName === "kitten") {
  redditParse.randomPost("cats").then((result) => {
    const resultObject = JSON.parse(result);

    while (resultObject.type != "image") {
      redditParse.randomPost("cats").then((result) => {
        const resultObject = JSON.parse(result);
    interaction.reply(resultObject.title + "\n" + resultObject.image);

I did some testing and found out that when the while loop gets activated, the repl crashes.

You’re overloading your memory and cpu resources with the loop. (That’s why it crashes)

You can use async/await to correct this.

Can you show what that would look like? I’m pretty new to javascript/node.

Oh sure! I will make some commentary but if you don’t understand some parts feel free to ask me.

if (interaction.commandName === 'kitten') {

    // Here we use the asynchronous function to get a random image of a kitten
    async function getKittenImage() {
        // Than you unitialize a variable to hold the result object
        let resultObject;
        do {
            // This is why the await keyword is important, it ensures that the loop will not continue until the promise is resolved
            const result = await redditParse.randomPost("cats");
            resultObject = JSON.parse(result);
            // If the type of resultObject is not "image", the loop will continue with a new request
        } while(resultObject.type != "image")

        // Once a post with type "image" is found, the loop will exit and the result is sent as a reply
        interaction.reply(resultObject.title + "\n" + resultObject.image)

Thanks it’s working now (:


you’re using a different resultObject binding in the second closure so the first resultObject isn’t updated in the outer scope
Here’s how I would do it

let resultObject;
do {
  resultObject = JSON.parse(await redditParse.randomPost("cats"))
} while(resultObject.type != "image");

for await to work, you need to make your callback async: async (interaction) =>


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.