0

I am connecting to a sql db and returning data on the view using res.json. The client sends a request - my server uses a mssql driver and a connection string to connect to that database and retrieve some data. So I've got a connection using GET, POST, ect.

However I am encountering a logical problem as I want to pass some data from the sql db to a module which will then use that data to prepare a json response. When I hard code an array with couple of parameters it works, but it don't know how to send a request from node.js to a db and propagate that array for a module to consume when a client sends a request. (When a client sends a request the module send a request to that db and the db returns some parameters which then the module can use to prepare a response.)

Any ideas? Could you point me in the right direction? How from a logical point of view such solution can work?

I am using node.js, express, mssql module to connect to db. I am not looking for specific code just to point me in the right direction, and if you've got any examples of course I'm happy to see those.

Mac_W
  • 2,927
  • 6
  • 17
  • 30

1 Answers1

1

You will probably need to have a chain of callbacks and pass data through them, something like this:

app.get('/users', function (req, res) {
    database.find('find criteria', function (err, data) {
        mymodule.formatData(data, function(err, json) {
            res.json(json);
        })
    });
});

So you just nest the callbacks until you have everything you need to send the response.

You need to get used to this style of programming in node.js. There are also some solutions to avoid too deep callbacks nesting - split your callbacks into individual functions or use async, promises, es6 generators.

Community
  • 1
  • 1
Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54