Reputation: 6281
Inside my AuthController, I am doing the following:
request.post({url: 'https://graph.api.smartthings.com/oauth/token', form: authData} , function(err, resp, body){
info = JSON.parse(body);
req.session.accessToken = info.access_token;
getEndpoint(req.session.accessToken, function(err, resp) {
if(err) {
//TODO: Handle error
console.log(err);
} else {
req.session.endpointUri = resp;
}
});
console.log("endpoint " + req.session.endpointUri);
res.view('test', {
accessToken: req.session.accessToken,
});
});
As you can see, I am trying to set 2 sessions, accessToken and endpointUri.
The accessToken
session saves just fine, and I can access it from other controllers, however my endpointUri
does not save.
I've tested the function and resp is being returned, and if I log out the session straight after setting it within the else statement it works.
If I try and log out the session outside of the else statement, it is undefined.
What is happening here?
Upvotes: 0
Views: 29
Reputation: 713
You want access the session value on an Async operation which is not completed when you return your view. Try:
request.post({url: 'https://graph.api.smartthings.com/oauth/token', form: authData} , function(err, resp, body){
info = JSON.parse(body);
req.session.accessToken = info.access_token;
getEndpoint(req.session.accessToken, function(err, resp) {
if(err) {
//TODO: Handle error
console.log(err);
} else {
req.session.endpointUri = resp;
console.log("endpoint " + req.session.endpointUri);
res.view('test', {
accessToken: req.session.accessToken,
});
}
});
});
By the way, this using nested callback is not the good pattern, try using bluebird library or asyncawait.
Upvotes: 2