Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback hell in multiple if, else if statements

I have function with data and callback parameters. The data is an object with many attributes and I have to validate these. I wrote multiple if, else if statements to do it, but it seems so disgusting to me.

function(data, callback) {

 if (data.a != 'x') {
   logger.log(...);
   return callback({status: false, code: 'x'});
 } else if (data.b != 'y') {
   logger.log(...);
   return callback({status: false, code: 'y'});
 } else if (data.c != 'z') {
   logger.log(...);
   return callback({status: false, code: 'z'});
 } else if (data.d != 'w') {
   logger.log(...);
   return callback({status: false, code: 'w'});
 }

 //... logic ...
 return callback({status: true});
}

I think It's not the appropriate way to do it.

like image 915
Tamás Mazuk Avatar asked Apr 12 '26 18:04

Tamás Mazuk


1 Answers

One way would be to factor the validation into a separate function:

function failureCode(data) {
    if (data.a != 'x')
        return 'x';
    if (data.b != 'y')
        return 'y';
    if (data.c != 'z')
        return 'z';
}

function (data, callback) {
    var code = failureCode(data);
    if (code) {
        logger.log(...);
        return callback({status: false, code: code});
    }

    //... logic ...
}

Also, don't forget to return from the "failed" branch.

like image 178
georg Avatar answered Apr 15 '26 07:04

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!