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

问题描述 投票:0回答:1

我的返回结果并没有让它一直回到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
        });
    });
}
mysql node.js
1个回答
0
投票

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

它应该被宣传以便用于承诺控制流程:

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;
};
© www.soinside.com 2019 - 2024. All rights reserved.