for bucle blocking express.js route

Issue

A loop stops the execution of a route on Express JS until it finishes, this can generate a timeout in the browser.

In the example it takes approx. 10 seconds to show the website (I need to execute the sleep function) , but I would like this for you to continue running on Background, and the route will be displayed immediately

Any suggestion?

app.get('/', function(req, res) {
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    let array = [1,2,3,4,5,6,7,8,9]

    for (const a of array) {
        console.log(a)
        await sleep(1000);
    }

    res.send('hello world');
});

Solution

If you want the response send immediately, then put the res.send() BEFORE your loop. You can still run code after you’ve sent the response – that code just can’t be involved in computing what the response will be because it will have already been sent.

app.get('/', function(req, res) {
    res.send('hello world');

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    let array = [1,2,3,4,5,6,7,8,9]

    for (const a of array) {
        console.log(a)
        await sleep(1000);
    }

});

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published