【发布时间】:2020-07-08 03:13:50
【问题描述】:
我正在尝试在 nodejs 中编写一个函数,该函数从 json 文件中读取有关用户的信息(我知道这不安全,只是一个练习),记录详细信息是否正确并发送响应。 我写了这个异步函数:
async function getUser(sUsername) {
fs.readFile('db/users.json', (err, data) => {
if (err) {
console.log(`An error has occured in getUser function`)
}
let users = JSON.parse(data)
userNamesFromFile = Object.keys(users);
console.log(`Data is: ${data}`)
console.log(`Users after parsing are: ${userNamesFromFile}\n`)
for (currUser in userNamesFromFile) {
`Currently checking comparing to user: ${currUser}\n`
if (currUser === sUsername) {
var oUser = new User(currUser, users[currUser].password);
return oUser;
}
}
})
}
我在这里称它为:
getUser(oBody.username.toLowerCase()).then(oFoundUser => {
console.log(`Finished the async function, found user ${oFoundUser}`)
if (oFoundUser) {
if (oBody.password.toString() === oFoundUser.password.toString()) {
console.log("Login successful")
res.statusCode = 200
req.session.username = oFoundUser.username;
}
else {
console.log("Wrong password")
res.statusCode = 401;
}
}
else {
res.statusCode = 401
console.log("No user with such a name exists")
}
res.send();
})
这是我在输入正确的用户详细信息时从服务器获取的日志:
Finished the async function, found user undefined
No user with such a name exists
POST /login 401 7.822 ms - -
Data is: {
"testuser1": {
"password": 12345
},
"testuser2": {
"password": 6789
}
}
Users after parsing are: testuser1, testuser2
看起来他是在说异步函数运行,然后才记录我从异步函数记录的信息。它甚至没有进入将用户与我刚刚从我的 json 文件中获得的内容进行比较的循环。 我将我想要对异步函数的返回值做的事情放在 .then 中。它不应该按照我期望的顺序运行吗?
谢谢,
本
【问题讨论】:
-
我将不得不查看文档,但您将回调和 Promise API 混合在一起似乎很像一个问题。
标签: node.js asynchronous promise fs readfile