1 回答

TA貢獻(xiàn)1775條經(jīng)驗 獲得超8個贊
嘗試這個
try {
let db = await MongoClient.connect(config.url, config.options);
} catch (err) {
console.log(`Catched: ${err}`);
}
async-await/sequential如果您想讓 try catch 工作,請嘗試以風(fēng)格編寫代碼。
在這里你可以看到你err在回調(diào)中得到第一個參數(shù),為什么它會去 catch 塊?func1().then().catch()樣式代碼也會發(fā)生同樣的事情。
注意:如果要使用 await,請在函數(shù)名稱前使用 async 關(guān)鍵字。
例如:
async function test() {
try {
let db = await MongoClient.connect(config.url, config.options);
} catch (err) {
console.log(`Catched: ${err}`);
}
}
MongoClient.connect(config.url, config.options, (err, db) => {
if (err) { throw new Error('This is error'); }
});
添加回答
舉報