2

I am comsuming an APIRest, with Javascript, with fetch, as follows:

var c;

fetch('http://-:8080/CantidadPacientes')
  .then(a => a.json())
  .then( function(msg) {
        c = msg;
   });
   
console.log(c);  
 

But when I printed the variable "c", I get undefined. How I can will get the value of msg, in variable c. I need the value msg outside the fetch, before the execution of console.log("c")

Brayme Guaman
  • 175
  • 2
  • 12
  • For more info read: ]https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – jfriend00 Sep 20 '18 at 20:26
  • "*I need the value `msg` before the execution of `console.log("c")`*" - but at that point in time, the value *doesn't exist yet* - it's asynchronous! Your only choice is to move the `console.log("c")` inside the `then` callback. – Bergi Sep 20 '18 at 20:54
  • then how can I wait for this value to arrive, because I need to load a component with that value after fetch, and I only get an undefined value on my web page. – Brayme Guaman Sep 20 '18 at 21:06

1 Answers1

2

By the time fetch is resolving the promise the line console.log(c) is already invoked.

Try moving it inside the callback:

var c;

fetch('http://-:8080/CantidadPacientes')
  .then(a => a.json())
  .then( function(msg) {
        c = msg;
        console.log(c); 
   });

You can test it with a simple Promise.resolve.

Your code example (undefined):

var c;

Promise.resolve('hi').then((msg) => {
  c = msg;
});
   
console.log(c);  

And inside the callback:

var c;

Promise.resolve('hi').then((msg) => {
  c = msg;
  console.log(c);
});

Edit
As a followup to your comment:

I need the value of "c", outside the block "fetch"

This is an asynchronous call. That means all of the global code (execution context) will run to completion and only then the callback (micro task in this case) will be allowed to continue.
As stated by others in comments, there are a lot of questions and great answers explaining asynchronous JavaScript.
Just follow the links.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99