Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js pass a callback?

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 :

  • Create the request
  • Upon receiving response, check for errors.
  • If errors are not found, send data back to caller of getAccessToken().

This is more of a learning Node.js async question , I've tried a few things and figured I'd ask some experts.

like image 325
Jeff B. Avatar asked Jun 26 '26 04:06

Jeff B.


1 Answers

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.

like image 159
Davin Tryon Avatar answered Jun 27 '26 19:06

Davin Tryon