Search code examples
javascriptpromisefetch-api

Retrieve value of variable outside function


I want to retrieve value of variable outside function(response). How can I do? please help!

<script>

    Test();

    function Test(){
      var c = "";
      filter();

      function filter(data) {
        c = data;
        console.log(data);
      }

       var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
       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);
          filter(response[0].name);
       });

    }

</script>

My result is find with "dara@" but have undefined like this:

undefined
"dara@"

Solution

  • One option is to await it:

    Test();
    async function Test(){
      var c = "";
      filter();
      function filter(data) {
        c = data;
        console.log(data);
      }
    
       var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
       const responseJSON = fetch(url)
         .then(response => response.json()) 
         .then((responseJSON) => {
            //console.log('Success:', response[0].name);
            filter(responseJSON[0].name);
            return responseJSON;
         })
         .catch(error => console.error('Error:', error))
        console.log(`got ${responseJSON}`);
    }