1

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.

Sefas
  • 89
  • 5

2 Answers2

2

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

Amadare42
  • 415
  • 3
  • 14
2

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.

bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • The `.then()` function is a way of handling Promises until a promise is resolved, which is, in other words, turning a non-blocking asynchronous function into synchronous form. – MTN Jul 03 '20 at 13:30
  • @Mastermind yea but i was talkin about the function inside `.then()` in this case the arrow function with the argument `data` witch is synchronouse and gets executed after the promise resolves – bill.gates Jul 03 '20 at 13:33