nodejs express 为什么不返回 res?

问题描述

如果 isBookmark 为真,我想完成 输入 then 下面和 console.log(1);这有效,我希望它不起作用

checkLecture(addLectureinformation)
        .then(() => {
            return insertLecture(addLectureinformation);
        })
        .then((succesInsertLecture) => {
            if (true) {
                return res.status(200).json(succesInsertLecture);
            } else {
                return Promise.all([1]);
            }
        })
        .then(num => {
            console.log(1);
        })

帮助

解决方法

您不能跳过承诺链中的步骤,但您可以移动最后一个 then 如果您已经返回响应,则不会调用它:

checkLecture(addLectureInformation)
        .then(() => {
            return insertLecture(addLectureInformation);
        })
        .then((succesInsertLecture) => {
            // this should be other condition,because this will be true always and "else" is not even needed/run
            if (true) {
                return res.status(200).json(succesInsertLecture);
            } else {
                // Moving the last "then" here,so it is not called is you have sent a response already
                return Promise.all([Promise.resolve(1)]) // Promise all expects an array of promises
                         .then(num => {
                           console.log(1);
                         })
            }
        });