ZeroByter ZeroByter - 1 year ago 43
SQL Question

Node.JS function to return the value of a async callback function

In Node.JS, I have a function to connect with a MySQL database, get a bunch of rows, and then return them as an array. My problem is with

code, I am using the
Node.JS module.

This is my function so far:

var async = require("async")
function get_all_channels_by_order(){
mysql_connection.query("SELECT * FROM channels ORDER BY listorder ASC", function(err, result){
callback(null, result)
], function(err, result){
return result
//return ?? somehow, return the value from the MySQL query?

The problem appears when the line to call for the function already checks for the return value even though it wasn't sent yet.

How can this be done? Is it even possible? I realize I can just not use this function and manually do the query when ever I need it but that would end up completely not organized and messy.

I previously asked this question 'Change a variable from outside it's scope' which was marked as a duplicate of 'Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference', that question talks about asynchronous code, not how to have a function return a value from it and I can not figure out how.


Due it's asynchronous code You've to use callback to get data.

You think if You use async package it will help You do return result?

  • No, You cannot.

Async package is helpful to get rid of callback-hell, when You've many functions that use result of previous function.

In Your case You don't need async.

Please read or watch tutorials about nodejs asynchronous behavior. For example this tutorial series: timeline 03:00 where explains blocking vs non-blocking code

So to get data after query execution is only this way:


function get_all_channels_by_order(callback){
    mysql_connection.query("SELECT * FROM channels ORDER BY listorder ASC", callback);

get_all_channels_by_order(function(err, result) {
  if(err) {