Pikachu
Pikachu

Reputation: 2003

Stop function after using callback

How to make callback to act like return inside function.

frontendProcessor.validateJSON = function(json, callback) {
if(!json) {
    callback("Validate JSON: Error, empty JSON variable", null);
} else {
    try {           
        var newJson = JSON.parse(json);
    } catch(err) {          
        callback("Validate JSON: Error, Something is wrong with JSON.", null);          
    };
    callback(null, newJson);
};
};

If error will be caught, I would like to callback function and stop frontendProcessor.validateJSON function from continue it's processing. Any right way to do it, or just tricky ways?

Upvotes: 0

Views: 2087

Answers (1)

adeneo
adeneo

Reputation: 318302

Move the other callback, and you could always throw an error if parsing the JSON is somehow critical to the app

frontendProcessor.validateJSON = function(json, callback) {
    if(!json) {
        callback("Validate JSON: Error, empty JSON variable", null);
    } else {
        try {           
            var newJson = JSON.parse(json);
            callback(null, newJson);
        } catch(err) {          
            callback("Validate JSON: Error, Something is wrong with JSON.", null);
        };
    };
};

frontendProcessor.validateJSON(json, function(err, result) {
    if (err != null) {
        var err = new Error(err);
        throw err;
    }

    // use result

});

Upvotes: 3

Related Questions