简体   繁体   中英

How to get result from function in other file in node.js

Trying to call database query from other javascript file in NodeJS.

Sample database file:

function addUser(user) {

  connection.connect(function (err) {
    if (err) {
        console.error('Error connecting: ' + err);
    }
    console.log('Connected as id ' + connection.threadId);
  });

  var sql = "INSERT INTO `mobile`.`main` (`userId`) VALUES (?);"
  var inserts = [user];


  connection.query(sql, inserts, function (error, results) {
    console.log('query');
    if (error) {
        return error;
    } else {
        console.log('Success Query');
        return results;                
    }
  });
  connection.end(function (err) {
    if (err) {
        console.error('Error connecting: ' + err);
    }
    console.log('Connection closed!');
  });
}

module.exports = addUser;

Sample main.js file:

app.get('/api/mysql/:user', function (req, res) {
  var user = req.params.user;
  addUsers(user)
  res.json({
    SQLResp: 'Query succes',
    result: addUsers.result
  });
});

How to get the result from the first file and use it as a response in the main js?

You need to pass a callback into your addUser function, and call it inside your connection.query with the results.

Currently, when you return, you're returning inside another callback, which means the data is more or less being thrown away.

That will also let you handle all of the error cases in a way you can tell the user about.

Welcome to stack overflow.

this is missing from your database file, How did you got connection there?

Here's a sample example over How to export database connection and use this to make calls from other files.

Also do read about callbacks-functions , Promises , async-await and Asynchronous functions of JavaScript . These are basics of JavaScript and also do go through NodeJS docs .

DB.js:

const MYSQL                     = require('mysql');

const connection = MYSQL.createConnection({
    host:                       'localhost', // url of db
    user:                       'root',
    password:                   'root',
    database:                   'dbName'
});

module.exports = connection;

Now will use this connection from other file to call database.

app.js:

const db = require('./DB'); // Path of your db connection file. I named it DB.js on same level as of app.js


function addUser(user) {

    // Since database calls are async in NodeJS thus using promises.
    return new Promise ( (resolve, reject) => {
        db.connect(function (err) {
            if (err) {
                console.error('Error connecting: ' + err);
                return reject(err);
            }
            console.log('Connected as id ' + connection.threadId);
        });

        var sql = "INSERT INTO `mobile`.`main` (`userId`) VALUES (?);"
        var inserts = [user];


        db.query(sql, inserts, function (error, results) {
            console.log('query');
            if (error) {
                return reject(err);
            } else {
                console.log('Success Query');
                return resolve(results);                
            }
        });

        db.end(function (err) {
            if (err) {
                console.error('Error connecting: ' + err);
            }
            console.log('Connection closed!');
        });
    });

}

app.get('/api/mysql/:user', function (req, res) {
    var user = req.params.user;

    addUsers(user)
    .then (result => {    // When addUsers will resolve promise will be in then.
        res.json({
            SQLResp: 'Query succes',
            result: result
        });
    })
    .catch(err => {        // If promise is rejected then on catch
        res.json({
            SQLResp: 'Query err',
            result: err
        });
    });
});

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