简体   繁体   中英

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 asynchronous code, I am using the async Node.JS module.

This is my function so far:

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

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:

mysql_connection.connect();

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) {
    console.error(err);
    return;
  }

  console.log(result);
});

I had some problems with error handling with NodeJS in the past too. After reading the NodeJS Error API it got much more clear.

I think it's always worth it to have a look.

https://nodejs.org/dist/latest-v4.x/docs/api/errors.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM