Alexander M.
Alexander M.

Reputation: 181

Javascript - callback function with predefined argument

I have predefined function, which supports callback to the second argument. I can't modify this function. How to pass callback function, so it will execute callback function with my argument and result it has received?

// predefined function, can't modify it ->>
function getEmail(uID, fn) {
    var result = { status: 'OK', data: { email: '[email protected]'} }; // answer for uID=13
    fn(result);
}
// <<- predefined function, can't modify it

var helper = {

    send: (uID, cb_function) => {
        getEmail( uID, helper.receive/*?[cb_function]?*/ ); // how to pass to the second argument cb_function?
    },

    receive: (/*?[result, cb_function]?*/) => {
        if ( result.status == 'OK' ) {
            cb_function(result.data);
        } else {
            alert('GetEmail result wasn\'t OK!');
        }
    },

}

helper.send(13, (a) => {
    // cb_function:
    alert( 'User email: ' + a.email );
});

Upvotes: 0

Views: 27

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074178

Usually, you use a wrapper function:

send: (uID, cb_function) => {
    getEmail( uID, (result) => {
        helper.receive(result, cb_function);
    });
},

Upvotes: 1

Related Questions