exports.createTour = async (req, res) => {
try {
const newTour = await Tour.create(req.body);
res.status(201).json({
status: "success",
data: {
tours: newTour,
},
});
} catch (err) {
res.status(400).json({
status: "fail",
message: err,
});
}
};
一切都在运行,直到我在这里添加了异步功能。这可能是什么原因?
答案 0 :(得分:1)
Tour.create内部发生了什么?
难道您是在Promise.reject()
内部调用new Promise((resolve,reject){...})
而不是使用reject()
?
下面的代码在我的“ bla”函数中同时拒绝和解决案件:
exports.createTour = async (req, res) => {
try {
const newTour = await bla();
res.status(201).json({
status: "success",
data: {
tours: newTour,
},
});
} catch (err) {
res.status(400).json({
status: "fail",
message: err,
});
}
});
let bla=()=>{
return new Promise((resolve, reject)=>{
//resolve("yay");
reject("I have my reasons");
});
}
我将尽力解释我所怀疑的情况- 但是如果不看代码就很难知道:
let create = ()=>{
// option 1. returns a new promise that resolves - your catch should work
Promise.resolve("great success");
return new Promise((resolve, reject)=>{
// option 2. creates a new promise in the new promise, which would explain the situation you described
Promise.reject("I need to be handled too - but im not");
// option 3. handles the locally created and rejected promise
Promise.reject("I need to be handled too").catch(x => console.log("handled"));
// option 4. rejects and is caught in the createTour function that called us - your catch should work
reject("I have my reasons");
// option 5. another function you call rejects and is not handled - would also cause what you described, for the same reason
let result = await func();
});
}
尝试查看您是否正在执行某种选择5或2-它会在诺言中创建一个诺言,该诺言会拒绝(并且不会被处理)。
另外,请注意,您可以在代码中使用完整的try {..} catch {..}代替
await Tour.create().catch(err => ...);
(类似于选项2)并专门处理拒绝
如果您想了解更多信息: https://blog.bitsrc.io/6-ways-to-implement-a-promise-in-javascript-9238aec9c17b