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.