I hope, you can help me with my async-await-issue..
I want so search in several databases, concat the results and return them as a json via express. It seems, that my "await db.query("SELECT..")" does not wait till the result arrived.
This is my DummySearchModule.js
const mysql = require('mysql');
const SearchModuleInterface = require('./SearchModuleInterface');
const SearchResult = require('./SearchResult');
class DummySearchModule extends SearchModuleInterface {
constructor() {
super();
var outer = this;
this.db = mysql.createConnection({
host: "127.0.0.1",
user: "db_user",
password: "db_pw",
database: "global_search"
});
this.db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
}
async search(search_term) {
var resultSet = [];
const dbResult = await this.db.query(`SELECT id, title, content, description FROM demo_entries`);
console.log("dbResult from db:");
console.log(dbResult[0]);
for(var element in dbResult[0]) {
var result = new SearchResult();
result.title = element.title;
result.description = element.description;
result.content = element.content;
result.date = Date.now();
console.log("title: " + element.title + ":: content: " + element.content);
resultSet.push(result);
}
console.log(resultSet);
return resultSet;
};
}
module.exports = DummySearchModule;
and this is my frontend-server.js
const express = require("express");
var dateFormat = require('dateformat');
const dummysearchmodule = require('./objects/DummySearchModule');
const server_port = 3000;
const search_modules = [new dummysearchmodule()];
[...]
app.get("/search/:search_term", (req, res, next) => {
search_modules.forEach(function(item, index, array) {
var results = item.search(req.params.search_term);
resultSet = searchInEveryModuleWithSearchterm(search_term);
});
res.json(resultSet);
});
And this is my output, and i don't know, why I get this..
Connected!
dbResult from db:
<ref *1> Query {
_events: [Object: null prototype] {
error: [Function (anonymous)],
packet: [Function (anonymous)],
timeout: [Function (anonymous)],
end: [Function (anonymous)]
},
_eventsCount: 4,
_maxListeners: undefined,
_callback: [Function (anonymous)],
_callSite: Error
at Protocol._enqueue (\frontend\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (\frontend\node_modules\mysql\lib\Connection.js:198:25)
at DummySearchModule.search (\frontend\objects\DummySearchModule.js:27:40)
at \frontend\frontend-server.js:25:31
at Array.forEach (<anonymous>)
at searchEveryModuleForResultWithSearchTerm (\frontend\frontend-server.js:24:20)
at \frontend\frontend-server.js:17:20
at Layer.handle [as handle_request] (\frontend\node_modules\express\lib\router\layer.js:95:5)
at next (\frontend\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (\frontend\node_modules\express\lib\router\route.js:112:3),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular *1], _timeout: null },
sql: 'SELECT id, title, content, description FROM demo_entries',
values: undefined,
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null,
_connection: <ref *2> Connection {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
config: ConnectionConfig {
host: '127.0.0.1',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'remote_user',
password: 'global_search',
database: 'global_search',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
localInfile: true,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631,
protocol41: true
},
_socket: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 174,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0
},
_protocol: Protocol {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
readable: true,
writable: true,
_fatalError: null,
_quitSequence: null,
_handshake: true,
_handshaked: true,
_ended: false,
_destroyed: false,
_queue: [Array],
_handshakeInitializationPacket: [HandshakeInitializationPacket],
_parser: [Parser],
[Symbol(kCapture)]: false
},
_connectCalled: true,
state: 'authenticated',
threadId: 23,
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false
}
If I log the output in the query function query("SELECT..", (err, res, fields) => console.log(res);}
, I get the correct output. My mysql-server is running in a docker-container.
Does anyone have any clue, o how I can archive my goal? Thanks a lot!!!
My understanding is that mysql does not support await/async out-of-the-box. You can try mysql2 instead (it is almost completely compatible with mysql API), for example it has a promise wrapper which you can use and have all these await/async
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.