Search code examples
javascriptparameter-passingconventions

Javascript function return best practice / convention


Say I have this

if ( ! chargeCreditCard() ) {
    // my custom error message here.
    // would like to display 'err' from
    // chargeCreditCard
    render("Could not charge cc")
} else {
    render("thanks! will ship soon")
}

chargeCreditCard() {
    Library.charge(cc_info, function(err, success) {
        if (err)
            return false

         return true
     }
}

What is typically done if i would like to display "err" from chargeCreditCard() in the if statement ?

Since chargeCreditCard returns true or false, I just render to the server a basic "could not charge cc".

Should be doing return err from inside chargeCreditCard and then do something like

var result = chargeCreditCard
if ( result !== true) {
    render(result)
} else {
    render('thanks! will ship soon')
}

Not a coding question, but a data flow question i suppose.


Solution

  • The option that makes more sense in this case, is returning a Promise. Promises are perfect tools to encapsulate asynchronous operations that may or may not succeed:

    chargeCreditCard()
      .then(_ => render("thanks! will ship soon"))
      .catch(err => render(`Could not charge cc. Reason: ${err}`));
    
    chargeCreditCard() {
      return new Promise((resolve, reject) =>
        Library.charge(cc_info, err => err ? reject(err) : resolve())
      );
    }
    

    Callback passing tends to make code over complicated, and even more when you begin chaining and nesting them. Sadly, promises are a relatively new tool and the vast majority of the NodeJS/Javascript opensource code heavily relies on callback passing.