简体   繁体   中英

How to call a function at start in Node-Express, with dbconnection

I'm a little bit newbie with Nodejs. I'm working in a Nodejs - express solution (as webservice of an angularjs web). I want to send and e-mail when MSSSQL database query gives back some information. This is working well for me. The problem is this function should be call in the app.js (when the nodejs server starts), because the function don't should respond to any frontend/web call.

The function:

exports.sendMailBuy = function(req, res) {
//do stuff
}

The app.js

var silkcartCtrl = require('./controllers/silkcart.controller');

I need to connect with the database, so I've tried to call the funciont in the same function db connection (I'm using Tedious):

dbsqlservertoken.connect().then(function(err, req, res) {
   console.log('Connection pool open for sql server');
   silkcartCtrl.sendMailBuy(req, res);
}).catch(function(err) {
  console.error('Error creating connection pool', err);
});

With this call I reach the function in the controller, but the req and res vars are empty, so the connection could not be done.

Any help will be appreciate.

Thanks in advance.

The .then() method is used when a Promise is returned. I'm not familiar with the libraries you're using, but your code indicates that connect() returns a Promise.

See Promises for more information.

In particular, the function passed to .then() takes a single argument which is the result resolved by the Promise. In your code, err is being assigned the result while req and res are undefined because the function only receives one argument.

req, res are not returned from connect callback function they are only acccessed using api requests eg app.post('/any route' , function(req, res))

You can use node_mailer module if you need req object to send email because with node_mailer you can send email without req object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM