使用Async/await函数和npm-mysql获取查询对象而不是结果 [英] Getting Query object instead of results with Async/await function and npm-mysql
问题描述
我有这个功能,它是async
,我正在尝试从npm-mysql
数据库进行简单的查询.
I have this function which is async
and i'm trying to make a simple query from npm-mysql
db.
let sortCategory = async (id) => {
try {
var sql = 'SELECT * FROM categories WHERE parent_id=?';
var results = await connection.query(sql, id);
// console.log(results);
return(results);
} catch(err) {
console.log(err);
return false;
}
}
但不是获取results
变量中的结果,而是获取查询对象.
But instead of results inside the results
variable i just get the query object.
Query {
_events:
[Object: null prototype] {
error: [Function],
packet: [Function],
timeout: [Function],
end: [Function] },
_eventsCount: 4,
_maxListeners: undefined,
_callback: undefined,
_callSite:
Error
at Protocol._enqueue (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:198:25)
at sortCategory (C:\Users\fedesc\Sites\borsalino\server\routes\categories.js:35:38)
at router.post (C:\Users\fedesc\Sites\borsalino\server\routes\categories.js:48:31)
at process._tickCallback (internal/process/next_tick.js:68:7),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular], _timeout: null },
sql: 'SELECT * FROM categories WHERE parent_id=\'0\'',
values: '0',
.... }
在对象中看到的query
是
sql: 'SELECT * FROM categories WHERE parent_id=\'0\'',
values: '0',
EDIT#1
INSERT
查询的异步/等待确实起作用.只是当我需要取回数据时,我才没有得到它.
an async/await for INSERT
query does works. it's only when i need to retrieve data back that i don't get it.
但是即使我确实有一些表应该返回,我也无法设法将结果返回. 我觉得对于mysql和异步调用我还是不太了解.
but i can't manage to get the results back even though i do have some in table that should return. i feel like there is something i still not quite understand about mysql and async calls.
谢谢大家.
推荐答案
正如我在文档 https中看到的那样://www.npmjs.com/package/mysql
connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
您的代码应该成为
var sql = 'SELECT * FROM categories WHERE parent_id=?';
connection.query(sql, [id], function (error, results, fields) {
if(error){
return error;
}
return results;
});
这篇关于使用Async/await函数和npm-mysql获取查询对象而不是结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!