【问题标题】:Node.js returning result from MySQL queryNode.js 从 MySQL 查询返回结果
【发布时间】:2013-08-24 02:10:51
【问题描述】:

我有以下从数据库中获取十六进制代码的函数

function getColour(username, roomCount)
{
    connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
    {
        if (err) throw err;
        return result[0].hexcode;
    });
}

我的问题是我在回调函数中返回结果,但 getColour 函数没有返回任何内容。我希望 getColour 函数返回 result[0].hexcode 的值。

在我调用 getColour 的那一刻,它没有返回任何内容

我试过做类似的事情

function getColour(username, roomCount)
{
    var colour = '';
    connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
    {
        if (err) throw err;
        colour = result[0].hexcode;
    });
    return colour;
}

当然 SELECT 查询已经完成,此时返回 colour 中的值

【问题讨论】:

    标签: mysql node.js callback


    【解决方案1】:

    如果你想使用 promises 来避免所谓的“回调地狱”,有多种方法。

    这是一个使用原生 Promise 和标准 MySQL package 的示例。

    const mysql = require("mysql");
    
    //left here for testing purposes, although there is only one colour in DB
    const connection = mysql.createConnection({
      host: "remotemysql.com",
      user: "aKlLAqAfXH",
      password: "PZKuFVGRQD",
      database: "aKlLAqAfXH"
    });
    
    (async () => {
      connection.connect();
      const result = await getColour("username", 2);
      console.log(result);
      connection.end();
    })();
    
    function getColour(username, roomCount) {
      return new Promise((resolve, reject) => {
        connection.query(
          "SELECT hexcode FROM colours WHERE precedence = ?",
          [roomCount],
          (err, result) => {
            return err ? reject(err) : resolve(result[0].hexcode);
          }
        );
      });
    }
    

    在异步函数中,您可以使用 await 表达式来暂停函数执行,直到 Promise 被解决或拒绝。这样getColour函数将返回一个带有MySQL查询的promise,它将暂停主函数的执行,直到返回结果或抛出查询错误。

    一种类似但可能更灵活的方法可能是使用 MySQL 库的 promise wrapper package,甚至是基于 Promise 的 ORM。

    【讨论】:

    • 谢谢,伙计。我花了 2 个小时寻找解决方案。
    【解决方案2】:

    您必须仅对回调中的 db 查询结果进行处理。就像。

    function getColour(username, roomCount, callback)
    {
        connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
        {
            if (err) 
                callback(err,null);
            else
                callback(null,result[0].hexcode);
    
        });
    
    }
    
    //call Fn for db query with callback
    getColour("yourname",4, function(err,data){
            if (err) {
                // error handling code goes here
                console.log("ERROR : ",err);            
            } else {            
                // code to execute on data retrieval
                console.log("result from db is : ",data);   
            }    
    
    });
    

    【讨论】:

    • 谢谢,虽然我仍然有同样的问题,我无法将回调的结果分配给变量(例如 var color = getColour(... - 这可能吗?
    • var colour = getColour(. 是不可能的。但是您仍然可以将颜色保留为全局变量并从回调中设置它。但是如果你想在 db fetch 完成时触发一些事情,你必须把它们放在回调中。
    • 谢谢你@mithunsatheesh。如何从 getColour 外部访问数据?
    猜你喜欢
    • 1970-01-01
    • 2018-03-06
    • 2015-01-29
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 2013-11-07
    相关资源
    最近更新 更多