gsdf
gsdf

Reputation: 285

Nodejs asynchronicity execution

I am working with my company database and I am trying to set up a route . The data that I get is an array of JSON of 1000 values.

Here's the function--

router.get('some_route', function(req, res, next){
var ress = [];
var name = req.params.name;
baWelcomeController.autoComplete(name).then(function(succ){
    var x = Object.values(succ[0][0]); 
    res.status(200).send(x);
}).catch(function(err){
  res.status(404).send(err);
    console.log("error in router.get", err);
});

});

Now look at the object.values part of my code , from internet i got to know its an O(n) function so nodejs should push it into the call-stack and in the meanwhile execute other functions, but what is happening is I am getting the response as expected. The number of values in succ[] are 1000, so I wrote another function commenting Object.values and writing a for loop instead-

router.get('some_route', function(req, res, next){
var ress = [];
var name = req.params.name;
baWelcomeController.autoComplete(name).then(function(succ){

    var x = 0;
    for(var i = 0; i <= 1000; i++)
        x += i;
    res.status(200).send(x);
}).catch(function(err){
  res.status(404).send(err);
    console.log("error in router.get", err);
});

});

Now I don't get value of x as response I get an empty object. I am finding this behavior weird! Could someone explain this to me.

Upvotes: 1

Views: 52

Answers (2)

Ratan Uday Kumar
Ratan Uday Kumar

Reputation: 6482

Hi Dear Since Node is Asynchronous Programming Language , internally it will skip functions which takes larger time for execution and it will first send response.

So u must use Synchronous Concept inside node

u can refer async package

sync package

Upvotes: 0

Gabriel Littman
Gabriel Littman

Reputation: 552

It think this is probably express turning your number into an object. According to the docs send can accept a Buffer, String, or Array.

https://expressjs.com/en/4x/api.html#res.send

Try something like: res.status(200).send({num: x});

Upvotes: 2

Related Questions