Kareivis
Kareivis

Reputation: 105

NodeJS - Make express server handle parallel query -

I am coding webapp that need to query a sql server. The problem is : I want that multiple clients can make request simultanly.



mysql=require('mysql')
express=require('express')

var app = express();
var pool = mysql.createPool({
    host: 'server',
    user: 'user',
    password: '',
    database: '',
    waitForConnections: true,
    connectionLimit: 100,
    queueLimit: 50
});




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

    var rows = pool.query(`query`,  (error, results)=>{
        if(error){
            
            console.log(error)
        }
        else{
            console.log(results)
            res.send('dsd')
        }
})
    
})


app.listen(80)

In this code, the second client must wait for the first client to finish before the server processes its request. This is not what i want.



mysql=require('mysql')
express=require('express')

var app = express();
var pool = mysql.createPool({
    host: '',
    user: '',
    password: '',
    database: '',
    waitForConnections: true,
    connectionLimit: 100,
    queueLimit: 50
});




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

    var rows = pool.query(`query`,  (error, results)=>{
        if(error){
            
            console.log(error)
        }
        else{
            console.log(results)
            
        }
})
    res.send('dsd')
})


app.listen(80)

With this code, the query is executed in concurrency but res.send() don't wait until the query is finished.

How can i modify this code in order that the query are executed in parallele and the res.send wait for the query response?

Thank you very much

Upvotes: 0

Views: 159

Answers (1)

jfriend00
jfriend00

Reputation: 708146

In this code, the second client must wait for the first client to finish before the server processes its request. This is not what i want.

Are you running two clients from different tabs in the same browser? If so, that sequencing is not the fault of your server, but is the browser deciding to wait for the first request to finish before sending a second identical request (in hopes of using a cached value).

Your first code is the correct way to code it. The second code block is just coded wrong as the asynchronous database result is not available yet when you try to send the result. You can't code that way with asynchronous callbacks.

How can i modify this code in order that the query are executed in parallele and the res.send wait for the query response?

The first code block is the way to write your Express code. There's nothing wrong with it. If two requests are getting serialized, then it's either happening on the client or in the database, not in your Express code.

Upvotes: 1

Related Questions