Micle
Micle

Reputation: 151

Nodejs prevent new request before send response to last request

How to prevent new requests before sending the response to the last request. on On the other hand just process one request at the same time.

app.get('/get', function (req, res) {
    //Stop enter new request
    someAsyncFunction(function(result){
         res.send(result);
         //New Request can enter now
    }
}

Upvotes: 0

Views: 883

Answers (2)

stefan_thedev
stefan_thedev

Reputation: 187

Even tho I agree with jfriend00 that this might not be the optimal way to do this, if you see that it's the way to go, I would just use some kind of state management to check if it's allowed to access that /get request and return a different response if it's not.

You can use your database to do this. I strongly recommend using Redis for this because it's in-memory and really quick. So it's super convenient. You can use mongodb or mysql if you prefer so, but Redis would be the best. This is how it would look, abstractly -

Let's say you have an entry in your database called isLoading, and it's set to false by default.

app.get('/get', function (req, res) {

    //get isloading from your state management of choice and check it's value
    if(isLoading == true) {
        // If the app is loading, notify the client that he should wait
        // You can check for the status code in your client and react accordingly
        return res.status(226).json({message: "I'm currently being used, hold on"})
    }

    // Code below executes if isLoading is not true        
    //Set your isLoading DB variable to true, and proceed to do what you have
    isLoading = true

    someAsyncFunction(function(result){
         // Only after this is done, isLoading is set to false and someAsyncFunction can be ran again
         isLoading = false
         return res.send(result)
    }
}

Hope this helps

Upvotes: 2

jfriend00
jfriend00

Reputation: 707416

Uhhhh, servers are designed to handle multiple requests from multiple users so while one request is being processed with asynchronous operations, other requests can be processed. Without that, they don't scale beyond a few users. That is the design of any server framework for node.js, including Express.

So, whatever problem you're actually trying to solve, that is NOT how you should solve it.

If you have some sort of concurrency issue that is pushing you to ask for this, then please share the ACTUAL concurrency problem you need to solve because it's much better to solve it a different way than to handicap your server into one request at a time.

Upvotes: 0

Related Questions