Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js returning result from MySQL query

I have the following function that gets a hexcode from the database

function getColour(username, roomCount) {     connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)     {         if (err) throw err;         return result[0].hexcode;     }); } 

My problem is that I am returning the result in the callback function but the getColour function doesn't return anything. I want the getColour function to return the value of result[0].hexcode.

At the moment when I called getColour it doesn't return anything

I've tried doing something like

function getColour(username, roomCount) {     var colour = '';     connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)     {         if (err) throw err;         colour = result[0].hexcode;     });     return colour; } 

but of course the SELECT query has finished by the time return the value in colour

like image 841
Pattle Avatar asked Aug 21 '13 15:08

Pattle


People also ask

What is node js used for?

Node. js is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It's used for traditional web sites and back-end API services, but was designed with real-time, push-based architectures in mind.

What is Sequelize in node JS?

Sequelize is a Node. js-based Object Relational Mapper that makes it easy to work with MySQL, MariaDB, SQLite, PostgreSQL databases, and more. An Object Relational Mapper performs functions like handling database records by representing the data as objects.


2 Answers

You have to do the processing on the results from the db query on a callback only. Just like.

function getColour(username, roomCount, callback) {     connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)     {         if (err)              callback(err,null);         else             callback(null,result[0].hexcode);      });  }  //call Fn for db query with callback getColour("yourname",4, function(err,data){         if (err) {             // error handling code goes here             console.log("ERROR : ",err);                     } else {                         // code to execute on data retrieval             console.log("result from db is : ",data);            }      }); 
like image 94
Mithun Satheesh Avatar answered Oct 09 '22 03:10

Mithun Satheesh


If you want to use promises to avoid the so-called "callback hell" there are various approaches.

Here's an example using native promises and the standard MySQL package.

const mysql = require("mysql");  //left here for testing purposes, although there is only one colour in DB const connection = mysql.createConnection({   host: "remotemysql.com",   user: "aKlLAqAfXH",   password: "PZKuFVGRQD",   database: "aKlLAqAfXH" });  (async () => {   connection.connect();   const result = await getColour("username", 2);   console.log(result);   connection.end(); })();  function getColour(username, roomCount) {   return new Promise((resolve, reject) => {     connection.query(       "SELECT hexcode FROM colours WHERE precedence = ?",       [roomCount],       (err, result) => {         return err ? reject(err) : resolve(result[0].hexcode);       }     );   }); } 

In async functions, you are able to use the await expression which will pause the function execution until a Promise is resolved or rejected. This way the getColour function will return a promise with the MySQL query which will pause the main function execution until the result is returned or a query error is thrown.

A similar but maybe more flexible approach might be using a promise wrapper package of the MySQL library or even a promise-based ORM.

like image 29
Goran Stoyanov Avatar answered Oct 09 '22 03:10

Goran Stoyanov