samedi 24 mars 2018

Get value of a variable inside a function (fetch)

I have one question about JavaScript, how to get value of a variable inside function. below is my code that I want to get value from var data = ret; to use outside function. My code have error with ReferenceError: data is not defined .Thank you!

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

  }




Aucun commentaire:

Enregistrer un commentaire