Express.js Routes Response Synchronously

Viewed 767

Problem

After 3 months of coding with Node.js Express.js, MongoDB and MSSQL i realized when a user run a complex query (it takes 15 seconds) other users is not getting any response until end of large query response.

Test Code

So i decided to create a simple app and test it.

const config = {
    port : 8080
};
const express = require('express');

/** RUN */
const app = express();
const http = require('http').Server(app);

/**
 * ROUTES
 */

app.get("/abc", function (req, res,next) {
    res.sendStatus(200);
    //next();
});

app.get("/", function (req, res,next) {
    var seconds = 10;
    var newDate = new Date().getTime() + seconds * 1000;
    var waitTill = new Date(newDate);
    while(waitTill > new Date()){
        console.log("waiting  : " + (newDate - new Date().getTime()));
    }
    res.sendStatus(200);
    //next();
});

/**
 * START
 */

http.listen(config.port,function (error) {
    if(error) logger.error(error);
    console.info("Server running on http://localhost:" + config.port);
});

Result

I made a request to localhost:8080/ and localhost:8080/abc with given order.

http://localhost:8080/ (10.02 s)

http://localhost:8080/abc (10.02 s) enter image description here

Conclusion

  1. Express.js route requests are async.
  2. Express.js route responses are sync.

Question

How can i create async responses with express.js route?

0 Answers
Related