0

I am working with Fetch api. I am facing scope problem for callback variable.

My Code is like this.

          var check; 

               fetch('http://localhost/react_task/dunckelsecure/php/credentialscheck.php'
        ).then(function (res) {
            return res.text();
        }).then(body => {
            console.log('body is ', body);
            // update
            check = "hey";
        });
         // how to declare value of check globally
        console.log('set body contain value is', body);

How to get value of body outside that

Any help regarding this...

Update.. how to access check variable globally

Manpreet Oberoi
  • 385
  • 3
  • 4
  • 13
  • 1
    You can't. It's not a scope problem. Fetch is asynchronous, you can only access `body` after the promise resolves (in the `then` function). – Sergiu Paraschiv Sep 27 '16 at 12:05
  • @SergiuParaschiv code is updated.. how to access variables globally – Manpreet Oberoi Sep 27 '16 at 12:20
  • 1
    You can access it globally but only _after_ `.then` executes. And `.then` only executes after your server responds. `console.log('set body contain value is', body);` is executed _before_ the server responds and `.then` is called. So first of all it's not a scope issue, it's just that at the moment you are trying to use `body` it's not yet set. You could `var bodyVarOutsideThen = '';` and then `bodyVarOutsideThen = body` inside `.then` but you still won't see the value coming from the server in `console.log('set body contain value is', bodyVarOutsideThen);` – Sergiu Paraschiv Sep 27 '16 at 12:23

0 Answers0