Search code examples
node.jsexpressknex.js

Having problem with calling external functions


I have a api server based on nodejs, connected to MySQL database using knex npm package for database (CRUD) actions, and express for req and res handling,

imagine I have a controller file, which is doing insert into database:

inside this file I am getting home_name as req.body and generate new ID and the insert it to database:

../controller/home.controller.js

var idGenerator = require('../utils/idGenerator');
var home = {
              id: idGenerator.generateID(), 
              name: req.body.name
           };

and the generateID is an exported function which is checking last generated ID in database and if there is one then +1 and return otherwise generate new random one.

../utils/idGenerator.js

function generateID() {
  knex('home').select("max(id)" as lastID)
    .then((lastID) => {
      if (lastID) {
        return parseInt(lastID) + 1;
      } else {
         //Generate new ID and return
      }
    })
}

module.exports.generateID = generateID

id: idGenerator.generateID is undefined

How to fix this issue?


Solution

  • so this is an async issue. the problem is that your generateID() function is asyncronous as it makes a DB call. You do not wait for async from the controller before processing. you COULD do something like this:

    var idGenerator = require('../utils/idGenerator')
    idGenerator.generateID().then(id => {
        var home = {
              id: id 
              name: req.body.name
           };
        // If using mongoose, you need to call res.send() in this promise callback.
    })