0

So i've been searching around the website for a soultion and came across something that has worked for a user previously and tried to copy how it was done just to test out using a callback function to return a result from a query would work, but I'm having problems. Here's my code

dbfunctions.js

   const connection = require('../helpers/connection');

   function getUserInfo(userID, dynamicField, callback) {
    var query = connection.query("SELECT * FROM subgutter WHERE name = 'random'");
    query.on('result', function(row) {
        callback(null, "row.dynamicField");
    });
  };

  module.exports = getUserInfo();

g.js

const express = require('express');
const router = express.Router();
const connection = require('../helpers/connection');
const dbfunctions = require('../helpers/dbfunctions.js');

 dbfunctions.getUserInfo(8, "test", function(err, result) {
    console.log(err || result);
});

this is giving me in dbfunctions.js callback is not a function

Not sure why there's a down-vote if someone could tell me how I can improve this question I'd appreciate it..?

2
  • Check to see if callback is undefined inside the on result event trigger. Commented May 14, 2017 at 16:02
  • yes it is undefined, do you know why this is? Commented May 14, 2017 at 16:51

1 Answer 1

2

You have to export getUserInfo as module.exports.getUserInfo = getUserInfo; or module.exports = {getUserInfo:getUserInfo}. In your case module.exports is the result of getUserInfo() (called without argument) and this throws your error.

Sign up to request clarification or add additional context in comments.

2 Comments

This works, but I have a follow up question. Is there a way to set the callback result to a variable without making the variable global? let gutterId = null; dbfunctions.gutterNameToId("random", function(result) { gutterId = result; });
If you define your variable in a given scope, it will be accessible only for upper scopes. In your example gutterId is global but you can do function(result) { let gutterId = result; }) and process your data in your callback function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.