0

So when running the following code, the response of the console.log(ba) is undefined But when I try this in the Chrome V8 Console I get the correct output I'm expecting. I'm not completely sure what is going on here.

    let ba;
    
    function Setqa() {
      ( async() => {
          await fetch('questions.json')
            .then(res => res.json())
              .then(async(data) => {
                ba = await data;
            });
      })();
    }
    
    Setqa();
    
    console.log(ba);

The contents of the json file are the following:

"questions": [{
            "questionType": "multiple",
            "question": "How is the weather",
            "answers": "",
            "questionAnswer": ""
        },
        {
            "questionType": "multiple",
            "question": "How are you today?",
            "answers": "<textarea rows='5' class='textArea'></textarea>1",
            "questionAnswer": "textPurpose1"
        }
    ]
Jerry 0
  • 3
  • 3
  • The problem with Chrome Console is it will update the value if the variable reference didn't change. and you open the console later. try this : `let c =()=>{ let b={} console.log(b) setTimeout(()=>{b={hi : 'gg'}},5000) }; c()` try first to open the console output before 5000ms then run again and open the console output after 5000ms and see the difference. and back to you question your issue is that you are printing the `ba` before it actually resolves – Tawfik Nasser Sep 26 '20 at 20:27

1 Answers1

0

I guess that should work

    let ba;
    
    function Setqa() {
      return fetch('questions.json')
            .then(res => res.json())
              .then(async(data) => {
                ba = await data;
            });
    }
    
    Setqa().then( () => console.log(ba) );
    

But a better approach would be

async function setQa(){
   const res = await fetch('questions.json');
   return res.json();
}

let ba = await setQa();