我有一條非常簡單的路線
router.get('/', async (req, res, next) => {
try {
const allEmployees = await employees.find({});
res.json(allEmployees);
} catch (error) {
next(error);
}
});
它作業正常。但是在我用catch. 它停止作業并拋出UnhandledPromiseRejectionWarning:
router.get('/', async (req, res, next) => {
const allEmployees = await employees.find({}).catch(next)
res.json(allEmployees);
});
似乎next在第二個版本中沒有正確呼叫。但是兩者在 JavaScript 中應該是等價的。不知道為什么第二個在 Express 中壞了。
uj5u.com熱心網友回復:
兩者在 JavaScript 中應該是等價的
不,他們不是。
Promise.prototype.catch()回傳一個新的 Promise,它使用回呼的回傳值決議。由于next()回傳void,此代碼...
employees.find({}).catch(next)
回傳一個成功的承諾,用undefined. next()將在失敗時呼叫,但沒有什么可以阻止您的其余代碼呼叫res.json(undefined).
如果您想使用Promise原型方法,則等效為
router.get('/', (req, res, next) => {
employees.find({}).then(res.json).catch(next);
});
如果你想繼續使用async/await并且最終的承諾失敗,你需要這樣的東西
router.get("/", async (req, res, next) => {
const allEmployees = await employees
.find({})
.catch((err) => Promise.reject(next())); // rejected result
res.json(allEmployees);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512437.html
下一篇:等待函式創建修改后的陣列
