Home > Mobile >  My node.js infinite loop stops working without no errors
My node.js infinite loop stops working without no errors

Time:12-01

I have an asynchronous function in Node.js I am calling over and over again. It basically fetches some data from API, processes it and this repeats forever. I have wrapped the whole function inside a try catch block with a finally statement, which calls the function again.

It looks like this:

async function infiniteLoop()
{
    try
    {
        console.log(Date.now())
        const response = await axios.get(...) // fetch data

        await Promise.all(response.data.entities.map(async (entity) => 
        {
            const product = new Product(entity)
            await product.resolve()
        }))
    }
    catch (e)
    {
        console.error(e)
    }
    finally
    {
        setTimeout(() => infiniteLoop(), 1000)
    }
}

The thing is that this infinite loop is sometimes broken and I have no reason why. By breaking I mean that the function is no longer doing anything. I was thinking it may be stuck somewhere, but I am using only axios (with timeout set to 5000 ms) and prisma. Nothing is printed out to console in the catch block etc. The Node process does not ever crash if the infinite loop breaks.

The infinite loop breaks randomly. Sometimes it breaks after several hours, sometimes after few days.

CodePudding user response:

I believe it should be an issue in the API, like 429 API response etc.
console.error() writes to stderr, whereas console.log() writes to stdout as described in the official docs .

In a default run of Nodejs, both stdout and stderr go to the console of browser, but obviously, they could be directed in different places that you need to check.

Here below is a working example without API call.

function infiniteLoop()
{
    try
    {
        console.log(Date.now())
        
    }
    catch (e)
    {
        console.error(e)
    }
    finally
    {
        setTimeout(() => infiniteLoop(), 1000)
    }
}
infiniteLoop();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Instead of a function calling itself over and over again you could do setInterval

This is a delayed infinite loop that in this example triggers every 1000 mills.

setInterval(async () => {
    // do stuff here
    
}, 1000);

CodePudding user response:

while(true){
await infiniteLoop();
await new Promise(resolve =>  setTimeout(resolve, 1000));
}
  • Related