简体   繁体   中英

How to code a function to be used with or without callback on Javascript?

I'm wondering how (if possible) I can create the same function, with exactly the same functionality, but to be used with a callback or without it. Here is an example with the "wanted effect" that is not working:

function getUsers(req, res, onComplete) {
    // If the user is not logged in send an error. In other case, send data
    if (!req.session.session_id) {
        if (typeof onComplete === 'function') {
            onComplete({error: true, msg: 'You are not logged in'});
        } else {
            res.json({error: true, msg: 'You are not logged in'});
        }  
    } else {
        //Another similar code...
    }
}

It's not working because if I call "getUsers(req, res)", the typeof onComplete is always function, so I cannot detect when I call with or without the callback.

The exact problem is that I can call this function from inside my code, with callback (a normal call, like getUsers(req, res, function(cb) {//Do something with cb}); OR I can call this function from an AJAX call in my website, like http://localhost:8080/api/getUsers , what in that case is when it don't works.

In the last case I get typeof onComplete === 'function' as true, so I never get the else part executed. I'm supposing that the "request" done by the http call have more parameters than req&res, and that's the reason why onComplete is a function, instead of undefined.

The usual AJAX call is like this (javascript in the client side):

function getAllUsers() {
    $.ajax({
        url: '/api/getUsers',
        type: 'GET',
        success: function(data) {
            // Remove item and set as main topic the assigned on the server 
            printUsers(data.users[0]);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { 
            alert(XMLHttpRequest.responseText); 
        } 
    });
}

And the route defined in the config.json of my Node.JS to call the final function is like that:

{"path": "/api/getUsers", "method":"get", "callback": "api#getUsers"},

If you call getUsers without onComplete the value will be set to undefined. You can then check that case in your function.

function getUsers(req, res, onComplete) {
    // Set onComplete to default call back if it is undefined
    onComplete = onComplete || function(msg){ res.json(msg) };

    if (!req.session.session_id) {
        onComplete({error: true, msg: 'You are not logged in'});  
    } else {
        //Another similar code...
    }
}

See http://www.markhansen.co.nz/javascript-optional-parameters/ for more ways of doing this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM