0

I'm trying to assign var globally but getting "undefined". How should I assign a variable in order to get the address outside the jsonReader ?

When I checked log inside jsonReader it works fine but when I'm trying to assign it to a gloabl var it shows undefined.

var myaddress;
jsonReader('./data.json',(error,data)=>{
    if(error){
        console.log(error);
    }else{
        addresses = data.records.map(record => record.data.property_name);
        addresses.forEach(element => {
            myaddress = element;
            console.log(myaddress);
        });
    }
})

doc.render({
    propertyname: myaddress,
    propetytype: "",
    phone: "",
    description: "New Website",
});

data.json:

{
  "name": "test",
  "records": [
    {
      "position": 1,
      "data": {
        "employees": {
          "teams": [],
          "users": []
        },
        "address": "ABC 123 Street"
      }
     },
     {
      "position": 2,
      "data": {
        "employees": {
          "teams": [],
          "users": []
        },
        "address": "DEF 456 Street"
      }
     }
  ]
}
Kitty
  • 300
  • 3
  • 12
  • @Unkonwn User - Please share your views instead of downvoting so that I can improve the question – Kitty Oct 29 '22 at 04:08
  • wasn't me but the bit that is inside `(error, data) => { .. here .. }` runs _after_ the doc.render call does, so it basically just hasn't been set yet. Make sure your doc.render occurs after the variable is available :) – Luke Briggs Oct 29 '22 at 04:11
  • So how do I find out that var is assigned before doc.render ? – Kitty Oct 29 '22 at 04:14
  • Either move the doc.render call to inside the callback (so it's just after your addresses.forEach) or use the [async/ await pattern](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). Node.js favours asynchronous code meaning it won't wait for a file to be loaded from the disk or a network operation to complete - in your case it is essentially scheduling the file to be read as json and then continuing to the doc.render line, then some point in the (near) future the file loads and the callback runs. – Luke Briggs Oct 29 '22 at 04:20

0 Answers0