gpt4 book ai didi

javascript - 从嵌套的 Promise 返回错误

转载 作者:行者123 更新时间:2023-11-30 15:14:03 24 4
gpt4 key购买 nike

假设我有这段代码:

let queries = [Student.findById(idStudent), Actv.findById(idActv)];
Promise.all(queries)
.then(result => {

let student = result[0];
let actv = result[1];

if(student == null)
return Promise.reject('Student not found');
if(actv == null)
return Promise.reject('Actv not found');
if(student.actvs.indexOf(actv._id) != -1 || actv.studentsInscritos.indexOf(student._id))
return Promise.reject('Student already signed up');

Actv.find({field: '1234'})
.then(qr => {
if(qr == null)
return Promise.reject('No actv found');
//Do something else
})
.catch(err2 => {
//Error
})

})
.catch(err => console.log({"error" : err}));

当我执行第二个查询时,它不会返回任何结果,并且会抛出一个 Promise 拒绝。我怎样才能让外部 promise 捕获这个异常?

最佳答案

很简单。你必须还回去,不要在内心的 promise 中捕获它。

这应该有效:

let queries = [Student.findById(idStudent), Actv.findById(idActv)];
Promise.all(queries)
.then(result => {

let student = result[0];
let actv = result[1];

if(student == null)
return Promise.reject('Student not found');
if(actv == null)
return Promise.reject('Actv not found');
if(student.actvs.indexOf(actv._id) != -1 || actv.studentsInscritos.indexOf(student._id))
return Promise.reject('Student already signed up');

return Actv.find({field: '1234'})
.then(qr => {
if(qr == null)
return Promise.reject('No actv found');
//Do something else
})

})
.catch(err => console.log({"error" : err}));

关于javascript - 从嵌套的 Promise 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44723467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com