从嵌套的Promise返回错误

时间:2017-06-23 14:08:29

标签: javascript ecmascript-6 promise es6-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');

            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拒绝。我怎样才能让这个例外能够获得这个例外呢?

1 个答案:

答案 0 :(得分:2)

非常简单。你必须归还它,而不是在内心的承诺中抓住它。

这应该有效:

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}));