0

My return result doesn't make it all the way back to API endpoint. Do you see what I'm doing wrong?

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
        });
    });
}
Rod
  • 14,529
  • 31
  • 118
  • 230
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Marcos Casagrande Jun 09 '18 at 18:18

1 Answers1

0

query method accepts error-first callback that isn't affected by returned value. GetContracts.get doesn't return a promise, and awaiting won't do anything.

It should be promisified in order to be used in promise control flow:

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

Or preferably, use existing promise-based MySQL library like promise-mysql, something like:

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;
};
Estus Flask
  • 206,104
  • 70
  • 425
  • 565