如何向客户端发送响应并立即终止整个函数而不是 return 到下一个回调

How to send response to client and terminate whole function immediately and not return to the next callback

    router.post('/login', (req, res) => {
    let user;
    User.findOne({
        username: req.body.username
    }).then(_user => {
        if (!_user) {
            return res.status(401).json({
                message: 'Username or password is incorrect'
            });
        }
        user = _user;
        return bcrypt.compare(req.body.password, _user.passwordHash);
    }).then(valid => {
        if (!valid) {
            return res.status(401).json({
                message: 'Username or password is incorrect'
            });
        }
        try {
            const token = jwt.sign({ username: user.username, id: user._id },
            "somesecret", { expiresIn: '1h' }
            );
        }
        catch (err){
            console.log(err);
        }
        return res.status(200).json({
            token: token
        });
    }).catch(err => {
        console.log(err);
        return res.status(500).json({
            message: 'Internal Server Error'
        });
    })
});

从第一个 "User.findOne" 回调开始,我想将响应发送回客户端并立即终止该函数,但它只会 return 退出第一个匿名回调函数,并继续进行第二个回调匿名函数检查变量 "valid" 并且会发生意想不到的事情,例如第二次写入响应并导致更多错误。有没有更好的方法来实现所有这些?

假设你使用express js,你需要使用res/end才能结束响应。之后return。 https://expressjs.com/en/api.html#res.end

在评论中与你交谈后,我仍然不明白你为什么要连锁承诺,但如果你想按照自己的方式这样做,跳过 "then" 的一种方法是抛出错误,这会将您带到 "catch" 部分。 试试这个,然后告诉我这是否是您想要的行为。

而不是:

        return res.status(401).json({
            message: 'Username or password is incorrect'
        });

尝试:

        res.status(401).json({
            message: 'Username or password is incorrect'
        });
        res.end();
       throw new Error("Username or password is incorrect")

这会直接跳到最后。

如果这不是您希望的工作方式,您需要解释 - return 的用途是什么?你想 return 什么时候? 您的 return 和您的直接回复有区别吗? 流程对我来说不够清楚。

如果您想要更简洁的代码同时仍然使用 promises,您可以使用 async await。在这里阅读: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function