简体   繁体   English

JavaScript无法获取从then()调用返回到另一个then()调用的返回值

[英]JavaScript Unable to get value returned from a then() call to another then() call

I am trying to execute this code: 我正在尝试执行以下代码:

UserSchema.methods.generateAuthToken = function () {
    const user = this;
    const access = 'auth';
    const token = jwt.sign({_id: user._id.toHexString(), access}, 'abc123');

    user.tokens.push({access, token});

    user.save().then(() => {
        return token;
    });
};

In my express file, I have following code: 在我的快递文件中,我有以下代码:

app.post('/users', (req, res) => {
    const body = _.pick(req.body, ['email', 'password']);
    const user = new User(body);

    user.save().then(() => {
        return user.generateAuthToken();
    }).then((token) => {
        res.header('x-auth', token).send(user);
    }).catch((err) => {
        console.log(err);
        res.status(400).send(err);
    });
});

The problem is that the token returned from the user.save().then() call in first file never reaches the express code user.generateAuthToken() . 问题在于,从第一个文件中的user.save().then()调用返回的令牌永远不会到达快递代码user.generateAuthToken() What is the reason and how should I solve it? 原因是什么,我应该如何解决?

generateAuthToken has no return statement. generateAuthToken没有return语句。

If you want to return the promise that then returns, then you have to do so explicitly. 如果您想返回承诺then返回,那么您必须明确地这样做。

you need to update your schema to the following: 您需要将架构更新为以下内容:

 UserSchema.methods.generateAuthToken = function () { const user = this; const access = 'auth'; const token = jwt.sign({_id: user._id.toHexString(), access}, 'abc123'); user.tokens.push({access, token}); user.save().then(() => { return token; }); }; 

The generateAuthToken does not return a Promise in your code generateAuthToken不会在您的代码中返回Promise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM