Reputation: 99
I am abit confused by asynchronous mechanism in NodeJs. I a have router class below as you can see. I have two endpoint, When I have a request to endpoint '/a' it takes like 10 seconds to response. While this 10 seconds I can not have a request to endpoint '/b' although I used asynchronous code.
const express = require('express');
const fetch = require("node-fetch");
const router = express.Router();
router.route('/a')
.get(function (req, res) {
fetch(url)
.then(response => response.json())
.then(data => {
**SOME CODE BLOCKS, IT TAKES 10 Seconds.**
res.send(data)
}
);
});
router.route('/b')
.get(function (req, res) {
res.send("Hello");
});
module.exports = router;
Please somebody explain me this behavior.
Thanks.
Upvotes: 1
Views: 85
Reputation: 14904
The callback, thats the function inside .then()
.then(data => {
**SOME CODE BLOCKS, IT TAKES 10 Seconds.**
res.send(data)
}
The function itself is synchronouse. If you have have a big loop for example then it will block your main thread. A solution could be to go with worker threads. They dont run on the main thread and so it does not block.
Upvotes: 2
Reputation: 414
Unfortunately, you dind't provide code that takes 10 seconds, so we can only guess. If you actually having some heavy computation inside this block that actually takes this time, you out of luck. Node.js and JS in general single-threaded, so you cannot achieve executing multiple operations in the same time within single JS VM. You can fix this issue starting child process and asynchronously waiting for it to finish. You can start your research on this starting from this question: How to have heavy processing operations done in node.js
Upvotes: 2