[英]Call a function inside async function at a js class
嗨,我是javascript編程的新手。
我有一個節點快速項目,我正在嘗試在AuthenticationController類中創建一個登錄方法。
我的登錄方法現在是這樣的:
const User = require('../models/User')
class AuthenticationController {
async login(req, res) {
const { email, password } = req.body
console.log('step 1')
var hashPassword = await userPassword(email)
console.log(hashPassword)
console.log('step 2')
return res.status(200).json({ 'msg': 'Log in OK!' })
}
userPassword(email) {
User.findOne({ email: email }).exec(function(err, user) {
if (err) return err
else return user.password
})
}
}
但是我收到一個錯誤消息,說userPassword是未定義的,我不知道為什么。 所以我的疑問是:為什么會發生這種情況,以及如何正確進行?
我也檢查了這個問題,但是他們沒有幫助我:
我的控制台上的錯誤消息:
(節點:28968)UnhandledPromiseRejectionWarning:ReferenceError:userPassword未定義...
(節點:28968)UnhandledPromiseRejectionWarning:未處理的承諾被拒絕。 引發此錯誤的原因可能是拋出了一個沒有catch塊的異步函數,或者是拒絕了一個.catch()無法處理的承諾。 (拒絕ID:1)
(節點:28968)[DEP0018] DeprecationWarning:已棄用未處理的承諾拒絕。 將來,未處理的承諾拒絕將以非零退出代碼終止Node.js進程。
login
不是指userPassword
方法,而是指不存在的同名函數。
承諾應該是連鎖的,不是。 預期userPassword
返回一個Promise,但它使用了過時的Mongoose回調API。
顯示的UnhandledPromiseRejectionWarning
表示login
時未正確處理錯誤,應正確處理。 如此答案中所述 ,Express不支持promise,因此錯誤應由開發人員處理。
它應該是:
async login(req, res) {
try {
const { email, password } = req.body
var hashPassword = await this.userPassword(email)
return res.status(200).json({ 'msg': 'Log in OK!' })
} catch (err) {
// handle error
}
}
async userPassword(email) {
const { password } = await User.findOne({ email: email });
return password;
}
因為您沒有為諾言處理錯誤,所以此錯誤即將到來。 始終在try / catch塊中使用async / await。
try{
async login(req, res) {
const { email, password } = req.body
console.log('step 1')
var hashPassword = await userPassword(email)
console.log(hashPassword)
console.log('step 2')
return res.status(200).json({ 'msg': 'Log in OK!' })
}
}catch(e){
console.log(e)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.