[英]unable to call function to pass variable value from another javascript file
[英]JavaScript Unable to get value returned from a then() call to another then() call
我正在嘗試執行以下代碼:
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
沒有return
語句。
如果您想返回承諾then
返回,那么您必須明確地這樣做。
您需要將架構更新為以下內容:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.