繁体   English   中英

我想从mysql的connection.query中取出结果并将其保存在nodejs中的全局scope链中

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

我尝试通过存储可变的当前产品来得出结果。 但我不能在 function 之外使用它,所以我的数组返回空

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);

在此处输入图像描述

尝试使用 async/await 语法来获取结果

  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();
      }
    })()

使用此代码:

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM