Tour.create 内部发生了什么?
难道你是在 new Promise((resolve,reject){...}) 中调用 Promise.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