Reputation: 11
I have a function which should return an access token. Inside a function there is a request, which gives me the token. But I can not acces it in the main function.
Here is my code from inside a function:
var accessToken = 'test1';
request.post(authOptions, function(error, response, body) {
accessToken = body.access_token;
console.log('test2 ' + accessToken);
});
console.log('test3 ' + accessToken);
It gives the following result:
test3 test1
(node:14744) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use node --trace-warnings ...
to show where the warning was created)
test2 BQDzZHO1Eg99...
The accessToken gets the value inside the request as seen in test2, but when I retrieve it after the function, it hasn't got it yet. How can I use it after? eg. in function retrieve
Upvotes: 1
Views: 42
Reputation: 4785
When you do request.post
your code has to wait for a response from the server you are posting to. This response is handled in your function(error, response, body)
function (passed in as the 2nd argument to request.post
. But in the meantime the rest of your function will continue to be executed. I've added comments to try and explain this futher:
var accessToken = 'test1'; // First line of your code is executed first
// Now we execute request.post
request.post(authOptions, function(error, response, body) {
// This is only executed whenever the response is received. It may be many milliseconds later
accessToken = body.access_token;
console.log('test2 ' + accessToken);
});
// This is executed immediately after the `request.post`. Therefore accessToken will still be 'test1'.
console.log('test3 ' + accessToken);
Instead you can return a Promise
or use callbacks to get the accessToken from this function. Here is a basic callback function:
function getAccessToken(callback) {
request.post(authOptions, function(error, response, body) {
callback(body.access_token);
});
}
getAccessToken(function(myToken) {
// Here is your token.
});
Upvotes: 1