如果我在console.log中显示我的结果,但如果我返回它就不会

时间:2018-06-09 18:06:27

标签: mysql node.js

我的返回结果并没有让它一直回到API端点。 你看到我做错了吗?

app.js

const express = require('express');
const app = express();

app.use(express.static('client'));
var GetContracts = require('./contractsService');

app.get('/contracts', async (req, res) => {
    var results = await GetContracts.get();
    console.log(results);
    res.send(results);
});

module.exports = app;

contractsService.js

var mysql = require('mysql');
const config = require('./config')

var con = mysql.createConnection({
    host: config.HOST,
    user: config.USER,
    password: config.PASSWORD,
    database: config.DATABASE
});


exports.get = function () {
    con.connect(function (err) {
        if (err) {
            throw new Error('Error by Rodney')
        };
        con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
            if (err) {
                throw new Error('Error by Rodney')
            };
            return result;
            //console.log(result); //works
        });
    });
}

1 个答案:

答案 0 :(得分:0)

query方法接受不受返回值影响的错误优先回调。 GetContracts.get不会返回承诺,await将不会做任何事情。

为了在承诺控制流程中使用它应该被宣传:

exports.get = function () {
    return new Promise((resolve, reject) => {
        con.connect(function (err) {
            if (err) {
                reject(new Error('Error by Rodney'))
            };
            con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
                if (err) {
                    reject(new Error('Error by Rodney'));
                } else
                    resolve(result);
            });
        });
    });
}

或者最好使用现有的基于promise的MySQL库,如promise-mysql,类似于:

var mysql = require('promise-mysql');

const conPromise = mysql.createConnection({
    host: config.HOST,
    user: config.USER,
    password: config.PASSWORD,
    database: config.DATABASE
});


exports.get = async () => {
    const con = await conPromise;
    const result = await con.query("SELECT * FROM " + config.DATABASE + ".Contracts");
    return result;
};