I want to select node.js from mysql and then use the data I gotㅜㅜ

Asked 2 years ago, Updated 2 years ago, 34 views

var results=[]; // Empty array for results
connection.query('SELECT * from img_result_tb', function(err, rows, fields) {
if (!err){
    for(var i=0; i<6;i++){
        results.push(rows[i].resultId); // get only the parts that correspond to resultId
    }
    console.log('The solution is: ', results); // output normally
}
else
    console.log('Error while performing Query.', err);
});

The query statement callback function contains the desired information in an array called results, but that array cannot be written outside of the function. I'm going to put the numbers in and express the color corresponding to each number in javascript. How can I use the imported results array outside?

ps. Now, that code is written in a file called index.js, but if you write a document.write in index.js, the document is not defined. Why is that? ㅜㅜㅜ ㅜㅜㅜ

javascript node.js mysql

2022-09-22 10:35

2 Answers

Think about it.

Node works on the server side, not on the browser.

The document is on the client side. That is, it can exist in a browser.

The javascript used in node and the javascript used in HTML may have the same grammar, but the purpose is different.

Node is the server side. The client side handles the DOM with the javascript that the questioner says.

Don't get me confused.


2022-09-22 10:35

The answer above is for PS, and to find some answers to the original question... This appears to be a asyncronicity issue in JavaScript.

The functions defined in all of the examples above are functions called asynchronous callbacks. What it means is that it can be created, but it can't be executed immediately. If the function is setTimeout, it enters the event queue, AJAX callback runs only when the call occurs, and onload runs only when the DOM is ready. Source

So I think you should roughly do this. I haven't tested it, so try it.

// Defined everything in advance
var results=[];
// The scope problem of the results variable is also resolved.
var pushResults = function (rows) {
    // You can do i<6 if you want to get 5 of them, but you can do this if you want to get all of them.
    for (var i=0; i<results.length; i++) {
        results.push(rows[i].resultId);
    }
}

// Call only when needed
connection.query('SELECT * from img_result_tb', function (err, rows, fields) {
if (!err) {
    pushResults(results);
    console.log('The solution is: ', results);
} } else {
    console.log('Error while performing Query. ', err);
}});


2022-09-22 10:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.