This question already has answers here:
How do I return the response from an asynchronous call?
                            
                                (38个答案)
                            
                    
                    
                        Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                            
                                (6个答案)
                            
                    
                2年前关闭。
        

    

我有一个名为check的变量,它将收到一个“ True / false”值。通过一个名为checkUserExist()的函数。

在那之后,我有一个if语句来检查它是对还是错。

问题是我的if语句在“检查”从其调用的函数获取其值之前运行。因此检查仍未定义。

function createUser(){

    let userName = document.getElementById("create_username").value,
        password = document.getElementById("create_password").value;
    console.log("Create user")
    console.log("Username:", userName, "Password:", password)

    var check = checkUsersExist(userName)

    console.log("Svar fra checkUsers",check)

    if(check == "true"){
        console.log("UserName all ready exists")
    }else if(check == "false") {
        console.log("UserName is avaible")
    }else{
        console.log("An error has uccured")
    }
}
function checkUsersExist(userName){
    let headers = new Headers();
        headers.append('Content-Type', 'application/json');

    var init = {
        method: 'PUT',
        headers: headers,
        body: `{
            "userName":"${userName}"}`,
        cache: 'no-cache',
        mode: 'cors'
        };

    var request = new Request('http://localhost:3000/users/check', init);

    fetch(request)
        .then(response =>
            {
                console.log("Response", response, "Request sent to server", request)
                return response;
            })
        .catch(err =>
            {
                console.log(err)
            });

}


我已经坚持了很长时间。而且我不确定如何解决它。我在checkUserExist()中获取的确从我的路线中获得了我正在寻找的答案

如果您也对此感兴趣,这是我的路线。

module.exports = function (server) {
    server.put('/users/check', function (req, res) {
        console.log("")
        console.log("=========== NEW CHECK ============")
        console.log("")
        console.log("Kom til check på route")
        let userName = req.body.userName,
            check = "false";

        console.log("UserName received from Index.html =", userName)

        fs.readFile('./resources/users.json', 'utf8',
            function readFileCallback(err, data){
                if (err){
                    console.log(err);
                }
                else {
                    users = JSON.parse(data); //now its a object

                    for (i = 0; i < users.table.length; i++) {
                        if(users.table[i].userName == userName){
                            console.log("===Current Check===")
                            console.log("Table =", users.table[i].userName, "Index =", userName)
                            check = "true"
                        }
                    }

                    console.log("check værdi =", check)
                    res.json(200, check)
                }
            }
        );

    });


我正在使用Json文件和Cookies来提高我的技能,因此为什么我不在此项目中使用数据库。

最佳答案

您的checkUserExists将始终返回undefined,无论它是否快速完成,因为它是异步的。您需要做的是向您的checkUsersExist添加一个回调机制,以便在收到响应后调用您的回调。我无法验证我在下面提供的更新代码,但是您可以尝试一下。

function createUser() {

  let userName = document.getElementById("create_username").value,
    password = document.getElementById("create_password").value;
  console.log("Create user")
  console.log("Username:", userName, "Password:", password)

  checkUsersExist(userName, function(check) {
    console.log("Svar fra checkUsers", check)

    if (check == "true") {
      console.log("UserName all ready exists")
    } else if (check == "false") {
      console.log("UserName is avaible")
    } else {
      console.log("An error has uccured")
    }
  })
}

function checkUsersExist(userName, onSuccess) {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');

  var init = {
    method: 'PUT',
    headers: headers,
    body: `{
            "userName":"${userName}"}`,
    cache: 'no-cache',
    mode: 'cors'
  };

  var request = new Request('http://localhost:3000/users/check', init);

  fetch(request)
    .then(response => {
      console.log("Response", response, "Request sent to server", request)
      onSuccess(response);
      return response;
    })
    .catch(err => {
      console.log(err)
    });

}

关于javascript - Javascript,脚本运行太快? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48138161/

10-09 21:29