承诺返回未定义的节点js

时间:2018-05-01 00:15:11

标签: javascript sql-server node.js npm promise

我有一个连接到sql数据库的函数,查询它,将结果格式化为html表并返回html变量:

function getData() {
    return new Promise((resolve, reject) => {
        var sql = require("mssql");
        var dbConfig = {
            server: "server",
            database: "db",
            user: "user",
            password: "pw"
        }
        var conn = new sql.Connection(dbConfig);
        var req = new sql.Request(conn);
        conn.connect(function (err) {
            if (err) {
                console.log(err);
                reject(err);
                return;
            }
            req.query("SELECT * FROM table",
                (err, recordset) => {
                    // Here we call the resolve/reject for the promise
                    try {
                        // If the results callback throws exception, it will be caught in 
                        // the catch block
                        resolve(resultsCallback(err, recordset));
                    }
                    catch (e) {
                        reject(e);
                    }
                }
            );

            conn.close();
        });
    })
}

function resultsCallback(err, recordset) {
    var tableify = require('tableify');
    if (err) {
        console.log(err);
        throw err;
    }
    else {
        var html = tableify(recordset);
        html = html.replace('<table>', '');
        html = html.replace('</table>', '');
        return html;
    }
};

我这样称呼它:

getData().then((data)=>{console.log("Table data:",data);})
         .catch((error)=>{console.log("ERROR LOADING SQL:",error);})

但是,出于某种原因,此输出为:Table Data: undefined

我不确定为什么会这样发生。我是否正确地返回了数据?

1 个答案:

答案 0 :(得分:-1)

我认为您的resultsCallback不必要地处理错误处理

我试图用一些现代风格来清理你的榜样,希望它可以帮助你

const sql = require("mssql")
const tableify = require("tableify")

/**
* FORMAT RESULTS
*  - format sql records as html
*  - returns a string of html
*/
function formatResults(records) {
  return tableify(records)
    .replace("<table>", "")
    .replace("</table>", "")
}

/**
* GET DATA
*  - query records from a database
*  - returns a promised string of html
*/
async function getData({db, table}) {

  // open the sql connection pool
  const pool = await sql.connect(db)

  // query the database and format the results
  try {
    const results = await pool.request()
      .input("tablename", table)
      .query(`SELECT * from @tablename`)
    return formatResults(results)
  }

  // rethrow query errors
  catch (error) {
    error.message = `getData sql query error: ${error.message}`
    throw error
  }

  // always close the connection
  finally {
    pool.close()
  }
}

// USAGE EXAMPLE BELOW
;(async() => {

  const data = await getData({
    db: {
      server: "server",
      database: "db",
      user: "user",
      password: "pw"
    },
    table: "table"
  })

  console.log(data)

})().catch(error => console.error(error))