0

I have a variable called check, which will receive a "True/false" value. Through a function called checkUserExist().

And after that i have a if statement to check on whether or not its a true or false.

The issue is that my if statement runs before "check" gets its value from the function it calls. So check remains undefined.

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)
            });

}

I have been stuck on this for quite some time. And i am not sure how to resolve it. My fetch in checkUserExist() does get the answer i am looking for from my route

Here is my route should you be interested in looking at that as well.

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)
                }
            }
        );

    });

I am working with Json files and Cookies to improve my skills with that, hence why i am not using a Database with this project.

JakeTheDane
  • 105
  • 1
  • 1
  • 8
  • 1
    That's the tricky thing about asynchronous code. Your script is blowing right past the `checkUsersExist` because the `fetch`in that function runs asynchronously from the rest of that block. Promises will help you out a lot here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Chris Riebschlager Jan 07 '18 at 14:42
  • You order a pizza and as soon as you hang up the phone, you try to eat the pizza. – epascarello Jan 07 '18 at 15:34

2 Answers2

1

Your checkUserExists will always return undefined, regardless it finishes quickly or not, since it is asynchronous. What you need to do is to add a callback mechanism to your checkUsersExist, such that your callback is invoked upon receiving a response. I am not able to validate the updated code I am providing below, but you can give it a try.

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)
    });

}
orabis
  • 2,749
  • 2
  • 13
  • 29
  • Still will not work.... You can not return from an asynchronous method... – epascarello Jan 07 '18 at 15:35
  • I did not say that the asynchronous function will return a value. In the updated checkUsersExist, the method receives a callback parameter, onSuccess. onSuccess is called upon receiving a response from the server. – orabis Jan 07 '18 at 15:41
  • This actually works just perfect. I had to change up the fetch a bit tho. But it does exactly as i want it to now: fetch(request) .then(function(response){ // console.log("Response", response, "Request sent to server", request) return response.json(); }) .then(function(result){ console.log("Result = "+result) onSuccess(result); }) .catch(function(err){ console.log(err) }); So thanks for thee help! – JakeTheDane Jan 07 '18 at 15:54
0

Since this is an asynchronous call, the end of the function 'checkUsersExist' is reached before the Request receives a reply. Thus you get as result 'undefined'.

Try writing your function with a callback, replacing the return statement with the function call, and call it like that:

checkUsersExist(userName, 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")
    }

});
bla
  • 301
  • 2
  • 11