这是对先前问题的重写/简化,甚至更加简化,但希望这次不会造成混淆。看下面的代码:
const mysql = require('mysql-await');
const dbPool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
port: 8889,
user: 'admin',
password: 'admin',
database: 'cslabelsportal',
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock',
});
async function getUserByID(id) {
if (id) {
try {
const rows = await dbPool.awaitQuery(`SELECT * FROM users WHERE id = '${id}'`);
[user = null] = rows;
return user;
} catch (error) {
return null;
}
}
}
async function test() {
const user = await getUserByID(6);
}
test();
这是在node.js中运行的,但是我绕过了几乎所有内容,问题仍然存在,所以我假设这与node.js处理事情有关……或者,我不知道知道。我所知道的:
awaitQuery是一个创建诺言并返回诺言的函数。当一切顺利时,它将解决承诺,如果抛出错误,则应该捕获该抛出,然后拒绝该承诺。我就是这样读的:
awaitQuery(query, params) {
return new Promise((resolve, reject) => {
try {
if ( typeof params === `undefined` ) {
this.pool.query(query, (err, result) => {
if ( err )
throw err;
resolve(result);
});
} else {
this.pool.query(query, params, (err, result) => {
if ( err )
throw err;
resolve(result);
});
}
} catch ( err ) {
reject(err);
}
});
}
函数getUserByID使用await,应该等待,直到该诺言被兑现,然后“如果Promise被拒绝,则await表达式将抛出被拒绝的值”。因此,如果出现问题,则应该在getUserByID中创建一个异常。该异常应该可以在该函数的try ... catch块中捕获。
除了结果是这样
...code/node_modules/mysql-await/index.js:505
throw err;
^
Error: connect ENOENT /Applications/MAMP/tmp/mysql/mysql.sock
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1137:16)
--------------------
at ...code/node_modules/mysql-await/index.js:503:21
at new Promise (<anonymous>)
at PoolAwait.awaitQuery (...code/node_modules/mysql-await/index.js:500:12)
at getUserByID (...code/test/server.js:16:33)
at test (...code/test/server.js:26:22) {
errno: 'ENOENT',
code: 'ENOENT',
syscall: 'connect',
address: '/Applications/MAMP/tmp/mysql/mysql.sock',
fatal: true
}
首先导致错误的事实是完全正确的,如果您关闭数据库,mysql会不喜欢它。我不明白的是为什么我仍然看到异常以及需要采取什么措施来消除它。