0

Here are my codes:

app.get('/index/:name',function(req, res){
    connection.query('SELECT * FROM deneme',function(err, rows, fields){
        if (err) throw err;
        var paragraf = rows;
    });

    res.render('index', {
        title: req.params.name,
        para: paragraf
    });
});

But node can't reach 'paragraf' variable from inside of 'res.render'. Node returns

ReferenceError: paragraf is not defined

How can i reach paragraf variable from outside of asynchronous functio?

user1870012
  • 59
  • 1
  • 9

1 Answers1

0

This is not how an asynchronous method result is supposed to be used, because the rows will not be available until the query callback is called.

Try instead:

app.get('/index/:name', function(req, res){
    connection.query('SELECT * FROM deneme', function(err, rows, fields){
        ...

        res.render('index', {
            title: req.params.name,
            para: rows
        });
    });
});

This way you access and render the results (rows) once they are available.

Guido
  • 46,642
  • 28
  • 120
  • 174
  • Above codes are just example, I'm quering two more sql query. This is the way but for 'only one' query. – user1870012 Dec 02 '12 at 12:55
  • If you are making several queries and want to render some kind of final result you should chain your callback functions. You can also use libraries such as async (https://github.com/caolan/async) to help you in this task. Remember that node follows an asynchronous model, when you call "query" the code continues executing the next line of code (call to "res.render"), it does not wait for the results, that is why you need to pass a callback to the query function. – Guido Dec 02 '12 at 12:59
  • No you can't. If you define it as global, res.render can find the variable, but it is very likely that the variable value is undefined when res.render is called, because the data will not be available until the query callback is executed. – Guido Dec 02 '12 at 13:17
  • In a sense, i can't use three mysql query in same time without (github.com/caolan/async) ? – user1870012 Dec 02 '12 at 13:20
  • Please update your question to see at least to queries, to fully understand your problem. You can do the same without async chaining the callbacks: connection.query(..., function() { connection.query(..., function() { ... } }) – Guido Dec 02 '12 at 13:23
  • Yes, this is how nodejs works. Take a look at this related question: http://stackoverflow.com/questions/4234619/how-to-avoid-long-nesting-of-asynchronous-functions-in-node-js – Guido Dec 02 '12 at 13:33