How to get a value from mysql query outside the query statement?

后端 未结 2 1749
抹茶落季
抹茶落季 2021-01-26 18:27

Here is the function see below console.log

function quo (value){
    value = connection.query(
       \'SELECT role from `roles` where `id` = 1\' , 
       fu         


        
相关标签:
2条回答
  • 2021-01-26 19:05
    function quo (success){
        value = connection.query(
           'SELECT role from `roles` where `id` = 1' , 
           function (error, results, fields) {
               if (error) throw error;
               console.log('The role is: ', results[0].role);
               success (results[0].role);
           });
    }
    
    quo (function (role) {
       console.log(role);
       /* do something useful with the role that came back from the query */
    });
    
    0 讨论(0)
  • 2021-01-26 19:07

    tl;dr everything happens in a callback.

    You're tripping up on the asynchronous nature of Javascript. By the time your console.log(value); call runs, the query is not (necessarily) completed. So, there's no way for the result of the query to be available at that time.

    Many developers use a pattern like this, with a callback function to handle the next step when the query result arrives.

    function quo (success){
        value = connection.query(
           'SELECT role from `roles` where `id` = 1' , 
           function (error, results, fields) {
               if (error) throw error;
               console.log('The role is: ', results[0].role);
               success (results[0].role);
           });
    }
    
    quo (function (role) {
       console.log(role);
       /* do something useful with the role that came back from the query */
    });
    

    Promise objects make this sort of thing easier to read in node.js. But explaining them is beyond the scope of a Stack Overflow answer anyhow.

    0 讨论(0)
提交回复
热议问题