-1

How would I get the value of the variable data inside function myFunc()? Below is a snippet of my code. I want to retrieve a value at this instance var data = ret; to use outside the function console.log(data). The code returns an error with ReferenceError: data is not defined.

myFunc();


   function myFunc() {
    query().then(function(ret) {
        console.log('result', ret); // result "@dara"
        var data = ret;
   });

    console.log(data); // ReferenceError: data is not defined
   }



  function query() {
    var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
    return fetch(url, {
        method: 'GET',
      })
      .then(function(response) {
        return response.json();
      })
      .catch(function(error) {
        console.error('Error:', error);
      })
      .then(function(response) {
        //console.log('Success:', response[0].name);
        return response[0].name;
      });

  }
Johnny
  • 13
  • 1
  • [Possible duplicate](https://stackoverflow.com/questions/5786851/define-global-variable-in-a-javascript-function). (nope, it's async) – user202729 Mar 24 '18 at 08:31
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ayush Gupta Mar 24 '18 at 08:32
  • console.log(data); is synchronous. Fetching the data is asynchronous. – connexo Mar 24 '18 at 08:32
  • Just define the `data` variable in scope of `myFunc`. Now the `data` is defined within callback scope. – Alexander Mar 24 '18 at 09:02
  • just delcare the data variable at the start of myFunc – badboy24 Mar 24 '18 at 09:29

1 Answers1

0

var data = NULL or [] //add it outside the myfunc function.

John Willson
  • 444
  • 1
  • 3
  • 13