0

I am fairly new to javascript, and I have read many articles and similar questions in the forum about promises and fetch, but I could't find a solution in returning a value from fetch. I am trying to read a value from a JSON file by using javascript. For that reason, I made this function to read the value:

function getlastname(){
    
    var myname;

    return fetch('names.json')
        .then((response) => { 
            return response.json().then((data) => {
                myname = data[2].lastname;
                
                return myname;
            }).catch((err) => {
            
            })
        });
}

When I call this function with this code:

var lname= "";

getlastname().then((result) => {
        lname = result;
        console.log(lname);
      })

The variable lname has the right value, but when I am trying to use lname outside .then, it's value is undefined.

Could someone please help me as I don't know how to keep the value of the variable and use it later in the program. Thank you very much in advance.

christo
  • 1
  • 1
  • 1
    To be able to use it outside of the `.then`, you need to either add another `.then`, or make the rest of your code start from that `.then`. For example: `var lname = ""; getlastname().then((result) => { lname = result; keepGoing(); }); function keepGoing() { /* Here, you can use lname */ }` – blex Jan 15 '21 at 18:21
  • What I want is to use this variable as value of a button. Than you for your response, I will try it. – christo Jan 15 '21 at 18:33

0 Answers0