Currently working :
function getAccessToken ( callback ) {
request({
uri: oauth2_url,
method: 'POST',
form: {
grant_type: 'password',
client_id: client_id,
client_secret: client_secret,
username: username,
password: password
}
},
function tokenRequestResponse (error, response) {
if ( !error && response.statusCode == 200) {
// Send our data back to caller.
callback ( JSON.parse(response.body).access_token );
}
else {
console.log('Error: ' + response.statusCode);
}
});
}
What I'd like to accomplish:
function tokenRequestResponse (error, response) {
if ( !error && response.statusCode == 200) {
callback ( JSON.parse(response.body).access_token );
}
else {
console.log('Error: ' + response.statusCode);
}
}
function getAccessToken ( callback ) {
request({
uri: oauth2_url,
method: 'POST',
form: {
grant_type: 'password',
client_id: client_id,
client_secret: client_secret,
username: username,
password: password
}
}, tokenRequestResponse });
}
I'd like to avoid nesting tokenRequestResponse() unless that is the only way to have it work with the callback.
It should :
This is more of a learning Node.js async question , I've tried a few things and figured I'd ask some experts.
The most common way to solve this is to return a function that closes over the callback.
So something like this:
function tokenRequestResponse(callback) {
return function (error, response) {
if ( !error && response.statusCode == 200) {
callback ( JSON.parse(response.body).access_token );
}
else {
console.log('Error: ' + response.statusCode);
}
}
}
And then you can use it like this:
function getAccessToken ( callback ) {
request({
uri: oauth2_url,
method: 'POST',
form: {
grant_type: 'password',
client_id: client_id,
client_secret: client_secret,
username: username,
password: password
}
}, tokenRequestResponse(callback));
}
When you make the call to tokenRequestResponse(callback) the function returns a function that will be used for the request callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With