내 머리를 포장하는 데 문제가 주위 비동기/await를 구문비동기/기다리고 있습니다 예상되는 동작
이 코드에 "연결"심지어 콘솔에 기록 얻을 않는 이유를 내가 알아낼 수없는 것은 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');
}
감사합니다. 비동기 함수가 반환한다는 것을 알지 못했습니다. 나는 이것이 Promise보다 훨씬 더 좋은지 잘 모르겠습니다. 그렇다면 패러다임. – richbai90
@ richbai90 그것은'then' 호출을 중첩하지 않고 제어 구조를 사용할 수있게하는 문법적 설탕입니다. 그러나 의미는 동일하게 유지됩니다. 'await'없이 어떻게 보이는지에 대한 아래의 nem035의 대답을보십시오. – Bergi