node.js sync nested mysql queries

Source: https://www.codexpedia.com/javascript/nodejs-sync-nested-mysql-queries/

Node.js is asynchronous I/O that other processes can start and doesn’t have to wait for some long running input/output processes such read and write from files or databases.For example, you are running five queries in for loop, the result of each loop will be appended to an array. Right after the for loop, you are calling the callback function to get all the results, but the chances are you will get an empty array because the line after the for loop is executed before the lines in the for loop. The code snippet below demonstrates how to make sure all the queries are processed before make the callback function. It declares an counting variable pending and set it to the number of queries to be ran. After a query is executed successfully, decrease the pending by 1, call the callback function if when pending is equal to 0.

var mysql = require('mysql');
var pool =  mysql.createPool({
host : 'localhost',
user : 'root',
password: '',
database: 'test'
});

function getStudents(ids, cb) { 
    var students = [];
    var pending = ids.length;

    for(var i in ids) {
        pool.query('SELECT * FROM students WHERE id = ?', [ ids[i] ], function(err, stu){
            students.push(stu);
            if( 0 === --pending ) {
                cb(students); //callback if all queries are processed
            }
        });
    }
}

var ids = [1,2,3,4,5];
getStudents(ids, function(students){
    console.log(students);

});

The table used in the demonstration above.

CREATE database `test`;
CREATE TABLE `students` (
  `id` int(11) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `grade` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `students` (`id`, `name`, `grade`)
VALUES
    (1,'ken',90),
    (2,'jim',90),
    (3,'kay',57),
    (4,'jerry',57),

    (5,'wen',66);

Không có nhận xét nào:

StaticImage

  import React , { useEffect , useRef } from "react" import { StaticImage } from "gatsby-plugin-image" impor...