I want to take out the result from mysql's connection.query and save it in global scope chain in nodejs

非 Y 不嫁゛ 提交于 2021-02-11 13:02:14

问题


I tried bringing out result by storing in variable current product. But I cant use it outside the function, so my array returns empty

var connection = mysql.createConnection({
                host: config.config.mysql.opencart_local.host,
                user: config.config.mysql.opencart_local.user,
                password: config.config.mysql.opencart_local.password,
                database: config.config.mysql.opencart_local.database
                })
var query_current_products = 'select * from table;';
var current_products = [];

  connection.connect(function(err) {
                       if (err) throw err;
                       console.log("Connected!");
                       connection.query(query_current_products, function (err, result) {
                             if (err) throw err;
                             //console.log(result);
                            current_products = result;
                      });

                }
                )
console.log(current_products);

enter image description here


回答1:


Try to use async/await syntax to get your results

  const mysql = require('mysql'); // or use import if you use TS
    const util = require('util');
    const conn = mysql.createConnection({
   host: config.config.mysql.opencart_local.host,
     user: config.config.mysql.opencart_local.user,
      password: config.config.mysql.opencart_local.password,
      database: config.config.mysql.opencart_local.database
     });
    var current_products = [];
    // 
    var query_current_products = 'select * from table;';

    (async function getProducts () => {
      try {
        const rows = await query( query_current_products);
        console.log(rows);
        current_products=rows;
      } finally {
        conn.end();
      }
    })()



回答2:


use this code:

var query_current_products = 'select * from users';
var current_products = [];
function f() {
    return new Promise(resolve => {
        con.connect(function (err) {
            if (err) throw err;
            console.log("Connected!");
            con.query(query_current_products, function (err, result) {
                if (err) throw err
                resolve(result);
            });
        });
    })
}

async function asyncCall() {
    current_products = await f();
    console.log("outside callback : ", current_products);
}

asyncCall();


来源:https://stackoverflow.com/questions/58299557/i-want-to-take-out-the-result-from-mysqls-connection-query-and-save-it-in-globa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!