简体   繁体   中英

Javascript nested callbacks in for loop

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?

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.query is 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.query to 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`);
            });
        });
    }

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