0

I have 2 requests 1 /Fibonacci (takes ~10sec) and 2 /hello (immediately)

when I try to run 2page consecutive 'message' is coming after Fibonacci I am using postman for both get-http://localhost:3001/fibonacci post-http://localhost:3001/hello

So my code running synchronous but I want it asynchronous, I tried promise and await but they both did not work for me.

const express = require('express')
const app = express()
const bigInt = require("big-integer");

const port = process.env.PORT || 3001

app.get('/fibonacci',async (req,res) => {
   res.send(fibonacci(bigInt(700000)))
})

app.post('/hello',async (req, res) => {
   res.send("message")
})


const fibonacci = (num) => {
   var a = bigInt(1), b = bigInt(0), temp = bigInt
   while (num > 0){ 
      temp = a 
      a = (a.add(b))
      b = temp 
      num= (num.add(-1)) 
   }
  return b;
}

app.listen(port, () => {
    console.log('Server is up on port ' + port)
}) 

I expect the seen message immediately but it is coming after Fibonacci calculation.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
  • I think it is happening because of "fibonacci" function. I tried using timeout of 10sec for 1st api and i got 2nd api result immediately, after 10sec i got 1st result – Sudhakar Oct 14 '19 at 13:03
  • I *guess* you want to know how to make Postman run things conncurrently by POSTing a second request without waiting for the first one to complete. If my guess is wrong please [edit] your question.. – O. Jones Oct 14 '19 at 13:25
  • @Sudhakar Yes, but in that situation, "function" takes 10 more sec than the default. – Ozgur Gurcan Oct 14 '19 at 14:18
  • @O.Jones no problem about the postman, I think I need multithread as you said – Ozgur Gurcan Oct 14 '19 at 14:19

1 Answers1

3

Node.js runs asynchronously, but it is not multithreaded. So, once your node/express program starts running fibonacci() it can't run anything else until that function completes.

To keep your node/express program responsive, you must work out a way to do small chunks of the Fibonacci computation using setTimeout() to schedule them one after the other until the computation is complete. Using setTimeout() lets node.js suspend handling your computation to handle other things.

Chunking an algorithm like Fibonacci's takes some thought and plenty of testing. Doing that for you is beyond the scope of a StackOverflow answer. Plus, if such an answer were here, people might use it as a magic spell, rather than understanding it.

Here's another question with some useful answers. How to break up a long running function in javascript, but keep performance

Using a node worker thread for this function may also help. But all these things incur development time, testing time, and a complexity debt in your program.

O. Jones
  • 103,626
  • 17
  • 118
  • 172