Reputation: 5204
I'm having trouble wrapping my head around async/await syntax
What I can't seem to figure out is why in this code, does "connected" get logged to the console even when there is an error in the connection to 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');
}
Upvotes: 2
Views: 1766
Reputation: 35481
Async functions return promises so this
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');
}
Could be:
connect().then(isConnected => {
if (isConnected) {
console.log('connected');
}
});
Or you could await for the promise returned from connect()
as well, as Bergi demonstrated in his answer.
Upvotes: 1
Reputation: 664307
Remember that async function
s are still asynchronous, they will not block anything or magically wait before they return. Calling connect()
always returns a promise which is always truthy so "connected" will get logged immediately in every case.
If you want to wait for the connection, you will have to await
the result and wrap the if
statement in an async function
as well:
async function connect() {
try {
await connection();
return true;
} catch (e) {
console.error(e);
return false
}
}
(async function() {
if (await connect()) {
// ^^^^^
console.log('connected');
}
}());
Upvotes: 3