27

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

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

4

2 回答 2

61

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

});
于 2013-08-21T18:36:58.807 回答
12

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

这是一个使用原生 Promise 和标准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);
      }
    );
  });
}

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

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

于 2019-11-30T19:23:49.913 回答