2 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
所以你需要改變:
const connectToDatabase = new Promise((resolve, reject) => {
mongoose.connect(
process.env.DATABASE_URL,
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
.then(() => {
const database = mongoose.connection
database.on('error', err => {
logError(err);
});
database.once(
'open',
() => {
console.log('Connected to database...')
resolve(database)
}
)
})
.catch(reject)
})
你應(yīng)該改進(jìn)這段代碼:
database.on('error', err => {
logError(err);
});
因?yàn)橹灰诮⑦B接后出現(xiàn)錯(cuò)誤(如斷開連接),就會(huì)觸發(fā)此事件。
所以你不能對(duì)事件reject
做出承諾。您應(yīng)該配置重新連接resolve
open

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
通過這樣做:const connectToDatabase = new Promise((resolve, reject) => {...您Promise在頂層構(gòu)建一個(gè),然后在startServer. 這相當(dāng)于這樣做:
// Top level Promise rejection
Promise.reject('error');
其余代碼仍然有效,因?yàn)閍wait它適用于已經(jīng)解決的問題Promise(也可能Promise在等待時(shí)尚未解決),但您應(yīng)該構(gòu)建Promise內(nèi)部 a function:
try {
startServer();
} catch (err) {
console.log(err);
}
async function startServer () {
try {
await connectToDatabase();
} catch ( err ) {
throw err;
}
}
function connectToDatabase() {
return new Promise((resolve, reject) => {
mongoose.connect(
process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const database = mongoose.connection;
database.on(
'error',
err => reject(err));
database.once(
'open',
() => {
console.log('Connected to database...');
resolve(database);
});
});
}
有了這個(gè),您在創(chuàng)建后立即獲得new Promise only in的引用,然后它解決或拒絕并且可能的拒絕被捕獲并且不會(huì)冒泡到頂層。startServer
添加回答
舉報(bào)