I have the following situation. I do fetch
towards the API
one from github but now I need to take fetch
the variable from state
it, the thing is that as it is, the variable state
from the last one if
comes out as undefined. How can I access it?
fetch('https://api.github.com/user?access_token=' + access_token, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
}).then(res => res.json())
.then(user => {
var username = user.login;
var insert;
var state = false;
for (insert = 0; insert < res.length; insert++) {
if (username == res[insert].login) {
state = true;
}
};
});
if (state) {
res.json({
success: true,
access_token: body.access_token,
jwt: token
});
} else {
res.json({
success: false
});
}
Your problem is that you are declaring the variable
state
inside the methodthen()
, what you have to do is declare it outside and assign the value inside thethen()
You could return state from the fetch response as an argument to a new
then
token
In this case I have no idea where they come frombody
, it is specifically so that you have access tostate
What @Jorius has exposed you should not do under any circumstances. This is a very common cause of problems when dealing with asynchronous code.
In a nutshell, if you execute two asynchronous functions, the second one can be resolved first. There is no way to determine which will be resolved first, except for technical details like latency, etc.
To solve your problem, you can do the following:
state
inthen
(covered by @amenadiel).state
in a callback.Using async/await
This is a new feature coming this year with ES8 where you can wait for an async function to finish executing but not be blocking.
Being a syntactically synchronous code , you will be able to return
state
as in any function.Using callbacks
This is the one that was always used in ES5. There is no greater mystery, it is only passed a function which is executed when the processing is finished
state
:So, suppose the function is called
getAccessToken
: