异步功能执行顺序错误

时间:2020-03-27 11:22:31

标签: node.js asynchronous promise fs readfile

我正在尝试在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中。它不应该按照我期望的顺序运行吗?

谢谢

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我想使用回调是正确的答案。如果我理解正确,那么异步函数不会返回我所提供的“返回”值的承诺,但是我可以在异步函数的解析内部调用复出。这是正确的吗?

async function getUser(sUsername, callback) {
    return fs.readFile('db/users.json', (err, data) => {
        if (err) {
            console.log(`An error has occured in getUser function`)
        }
        let users = JSON.parse(data)
        userNamesFromFile = Array.from(Object.keys(users));
        for (let i = 0; i < userNamesFromFile.length; i++) {
            currUser = userNamesFromFile[i]
            if (currUser === sUsername) {
                var oUser = new User(currUser, users[currUser].password);
                console.log(`Returnign callback with ${oUser.toString()}` )
                return callback(oUser);
            }
            if (i === userNamesFromFile.length - 1) {
                return callback(false)
            }
        }
    })
}
getUser(oBody.username.toLowerCase(), 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();
        })

谢谢