I wrote a Total.js project.
When accessing the controller from the model, it gives an empty answer. Here is the model code.

exports.getTarifs = function(f) { // definitions/mysql.js // create a DB connection var tarifs = []; // waiting for wait('waiting') DATABASE(function (err, connection) { if (err != null) { return; } var sql ='SELECT * FROM `tarifs` WHERE `f_id` = {0}'.format(f); connection.query(sql, function (err, rows,c) { // Close connection connection.release(); if (err != null) { return; } // Shows the result on a console window tarifs.push(rows); }); }); return tarifs; }; 

This code is written on the controller.

 var tarifs = Tarifs.getTarifs(self.config.f); 

    1 answer 1

    The problem is in this line: return tarifs; That is the problem - in general, the very fact that you are trying to return something from an asynchronous request.

    Asynchrony - it infects the code. An asynchronous handler cannot be used synchronously — any code that uses asynchronous processing must itself become asynchronous.

    You should make the getTarifs function asynchronous — for example, add a callback to it. Something like this:

     exports.getTarifs = function(f, callback) { DATABASE(function (err, connection) { if (err != null) { callback(err); return; } var sql ='SELECT * FROM `tarifs` WHERE `f_id` = {0}'.format(f); connection.query(sql, function (err, rows, c) { // Close connection connection.release(); callback(err, rows); }); }); }; 
    • Thanks for the answer. But this also does not work. Function call var Tarifs = MODEL('Tarifs'); console.log(Tarifs.getTarifs(0)); var Tarifs = MODEL('Tarifs'); console.log(Tarifs.getTarifs(0)); he gives undefined - Alijon
    • Of course. Read again what I wrote: asynchrony infects all the code. If the getTarifs function has become asynchronous, then it must be called asynchronously. - Pavel Mayorov