【问题标题】:JavaScript Unable to get value returned from a then() call to another then() callJavaScript 无法获取从 then() 调用返回到另一个 then() 调用的值
【发布时间】:2018-12-27 09:33:15
【问题描述】:

我正在尝试执行此代码:

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

在我的快递文件中,我有以下代码:

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

问题是从第一个文件中的user.save().then() 调用返回的令牌永远不会到达快速代码user.generateAuthToken()。是什么原因,应该如何解决?

【问题讨论】:

  • 为什么要保存在generateAuthToken() 方法中?通过省略 user.save() 副作用并简单地返回 token,在 post 处理程序中返回单个 .save() 将完成您需要的所有节省。作为奖励,您的承诺链接问题将消失。

标签: javascript express mongoose promise


【解决方案1】:

generateAuthToken 没有return 语句。

如果你想返回 then 返回的承诺,那么你必须明确地这样做。

【讨论】:

  • 那我应该在哪里添加return语句呢?
  • 函数中最后一条语句的前面。 (即您在其中调用then() 的表达式)。
【解决方案2】:

您需要将架构更新为以下内容:

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

generateAuthToken 不会在您的代码中返回 Promise

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    相关资源
    最近更新 更多