Node.js 从 MySQL 查询返回结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18361930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:35:50  来源:igfitidea点击:

Node.js returning result from MySQL query

mysqlnode.jscallback

提问by Pattle

I have the following function that gets a hexcode from the database

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

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

My problem is that I am returning the result in the callback function but the getColour function doesn't return anything. I want the getColour function to return the value of result[0].hexcode.

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

At the moment when I called getColour it doesn't return anything

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

I've tried doing something like

我试过做类似的事情

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

but of course the SELECT query has finished by the time return the value in colour

但当然 SELECT 查询已经完成的时间返回值 colour

回答by mithunsatheesh

You have to do the processing on the results from the db query on a callback only. Just like.

您必须仅对回调的 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);   
        }    

});

回答by Goran Stoyanov

If you want to use promisesto avoid the so-called "callback hell"there are various approaches.

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

Here's an example using native promises and the standard MySQLpackage.

这是一个使用本机承诺和标准MySQL的示例。

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

In async functions, you are able to use the awaitexpression which will pause the function execution until a Promise is resolved or rejected. This way the getColourfunction will return a promise with the MySQL query which will pause the main function execution until the result is returned or a query error is thrown.

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

A similar but maybe more flexible approach might be using a promise wrapper packageof the MySQL library or even a promise-based ORM.

一种类似但可能更灵活的方法可能是使用MySQL 库的承诺包装包,甚至是基于承诺的 ORM。