我无法绕过异步/等待语法
我似乎无法弄清楚为什么在这段代码中,"连接"即使连接到mysql时出错,也会记录到控制台。
mongoose.Promise = Promise;
function connection() {
//return a promise to be consumed in an async function
return new Promise((resolve, reject) => {
mongoose.connect('mongodb://localhost/testdatabase');
let db = mongoose.connection;
let sw = mysql.createConnection({
host: 'localhost',
user: 'reporting',
Promise: Promise,
database: 'testdatabase'
});
//Only resolve if both database connections are made successfully
sw.then(() => {
db.on('error', (err) => {
reject(err);
});
db.once('open', () => {
resolve(db);
});
}).catch((e) => {
reject(e);
})
});
}
//Await connection and return true or false for more synchronous code style
async function connect() {
let connected = false;
try {
//should pause execution until resolved right?
await connection();
connected = true;
} catch (e) {
//Makes it here successfully
console.error(e);
connected = false
} finally {
return connected
}
}
if (connect()) {
//This code also gets fired?
console.log('connected');
}
答案 0 :(得分:3)
请记住,async function
仍然是异步的,它们不会阻止任何事情或在它们返回之前神奇地等待。调用connect()
总是会返回一个承诺,它始终是真实的,因此在每种情况下都会立即记录“已连接”。
如果您想等待连接,则必须await
结果并将if
语句包含在async function
中:
async function connect() {
try {
await connection();
return true;
} catch (e) {
console.error(e);
return false
}
}
(async function() {
if (await connect()) {
// ^^^^^
console.log('connected');
}
}());
答案 1 :(得分:1)
异步函数返回promises,所以这个
if (connect()) { // <--- connect() will return a promise
// and a promise always evaluates to a truthy value,
// that's why this code always runs
console.log('connected');
}
可能是:
connect().then(isConnected => {
if (isConnected) {
console.log('connected');
}
});
或者你可以等待connect()
从SI
返回的承诺,如Bergi demonstrated in his answer。