0

I have written a function as part of a module:

exec: function(pool, query, result) {

    pool.getConnection(function(error,connection) {

        if (error) {
            result({"code" : 100, "status" : "Error in connection database"});
            return;
        }  

        connection.query(query, function (error, results, fields) {
            if(error){
                result({"status": 500, "error": error, "response": null}); 
            } else {
                result({"status": 200, "error": null, "response": results});
            }
            connection.release();
            return;
        });

        connection.on('error', function(error) {
            result({"code" : 100, "status" : "Error in connection database"});
            return;
        });
    });
},

I am calling the function as follows:

sql.exec(pool, query, function(result) {
    console.log('result');
    console.log(result);
    res.render('index', { title: 'Express', results: result.response });
});

And I can get the results that I need in result.

However, I'd like the function to just return the object directly. Eg. Something like:

var result = sql.exec(pool, query);

I've tried various things, but I either end up with a function that returns undefined, or I have to use a callback to get the data, which is messy, particularly if I want to call the function multiple times.

Does someone know how I can rewrite my function to just return the result object?

Paul
  • 1
  • You can't in general, you need to use a `callback` or a `promise` for this. This would be the better way too ... – eisbehr Jun 07 '18 at 07:43
  • Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – eisbehr Jun 07 '18 at 07:44
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Estus Flask Jun 07 '18 at 10:58

0 Answers0