-1

I have nested functions which should not block the I/O.

 for(let i = 1; i < category_amount;i++){
        pool.query('SELECT COUNT(1) FROM threads_mphp WHERE category = ?',i,function(error, results1, fields) {
            console.log(i);
            pool.query('UPDATE category SET posts=? where category=?',[results1[0]['COUNT(1)'],i],function() {
                console.log(i);
            });
        });
    }

Both queries work with the same index i. I cannot use let for such purposes. The console.logs doesn't output as expected two same numbers in a row. How can I solve this problem?

Volkan Y
  • 119
  • 1
  • 8
  • 1
    Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Taplar May 27 '20 at 17:42
  • *" I cannot use let for such purposes"*: why not? *"The console.logs doesn't output as expected two same numbers in a row"*: why did you expect that? That would be expected when it was *synchronous* code, but it is asynchronous. It is quite likely that the outer `console.log` all execute before all the inner ones. Why is that a problem? – trincot May 27 '20 at 17:46

1 Answers1

0

I do not believe there is an issue here. The callback function (function(error, results1, fields)...) and subsequent UPDATE statement is invoked only when the results of pool.queryis completed. As a result, the logs may appear out of order since you are spawning the pool.query calls as fast it will allow you in the loop.

Add a logging statement before pool.queryto see exactly what is happening. I believe the logging will look something like

1 query! - called from loop
2 query! - called from loop
3 query! - called from loop
1 SELECT finished! - 1st callback is invoked and UPDATE dispatched.
4 query! - loop is still running!
2 SELECT finished!
1 UPDATE finished!
3 SELECT finished!
2 UPDATE finished!
...
for(let i = 1; i < category_amount;i++){
        console.log(`${i} query!`);
        pool.query('SELECT COUNT(1) FROM threads_mphp WHERE category = ?',i,function(error, results1, fields) {
            console.log(`${i} SELECT finished`);
            pool.query('UPDATE category SET posts=? where category=?',[results1[0]['COUNT(1)'],i],function() {
                console.log(`${i} UPDATE finished`);
            });
        });
    }
Alan Cheung
  • 244
  • 1
  • 7