Home > Mobile >  node.js function not returning value
node.js function not returning value

Time:09-29

this function works correctly and prints the value on the console but it's not return the value. I tried it like return resultArray but it does not work.

Following is the code:

const mysql = require('../database/server')

function inse() {
    let sql = `SELECT * FROM information_security`;
    mysql.connection.query(sql, [true], (error, results, fields) => {
        if (error) {
            return console.error(error.message);
        }
        else {
            var resultArray = Object.values(JSON.parse(JSON.stringify(results)))
            console.log(resultArray);
        }
    });
}

module.exports = { inse }

CodePudding user response:

Because of the callback in query(), inse cannot return the value. Instead, you have to pass a function, here called cb, to inse that will then do something with your resultArray:

function inse(cb) {
    let sql = `SELECT * FROM information_security`;
    mysql.connection.query(sql, [true], (error, results, fields) => {
        if (error) {
            console.error(error.message);
            cb(null, error);
        }
        else {
            var resultArray = Object.values(JSON.parse(JSON.stringify(results)))
            console.log(resultArray);
            cb(resultArray);
        }
    });
}

module.exports = { inse }

Then call your function like this:

function handleData(resultArray, error) {
  if(error) {
    console.log(error.message);
    return;
  }
  // manipulate the resultArray
}

inse(handleData);

CodePudding user response:

Because the arrow function (error, results, fields) => the return is called within the arrow function, so it returns there, not from the inse function. Also, calling console.error() also doesn't give a return type, so even if it worked you still get undefined as your answer.

  • Related