Javascript Cheatsheet - noduslabs/infranodus GitHub Wiki

Callback Functions in Javascript and Return Values

Suppose we have the following issue — we need to have a function return a certain value.

A wrong way to write this would be:

console.log(getValue('2392392'));

function getValue(sub_id) {
var chargebee_site = config.chargebee.site;
    var chargebee_apikey = config.chargebee.api_key;
    var chargebee_subscription = validate.sanitize(req.query.sub_id);
    chargebee.configure({site : chargebee_site,
      api_key : chargebee_apikey});
      chargebee.subscription.retrieve(chargebee_subscription).request(
      function(error,result){
        if(error){
          //handle error
          console.log(error);
        }else{
          console.log(result);
          return result;
        }
    });
}

The problem is that the return is in the nested function, so the actual getValue does not return anything.

What we need is a callback — a function that will be called from the code. So something like

getValue('2392392', function(err, response) {
   console.log(response);
});

function getValue (sub_id, callback) {
  if (config.chargebee && config.chargebee.site && config.chargebee.api_key) {
    var chargebee_site = config.chargebee.site;
    var chargebee_apikey = config.chargebee.api_key;
    var chargebee_subscription = validate.sanitize(sub_id);
    chargebee.configure({site : chargebee_site,
     api_key : chargebee_apikey});
    chargebee.subscription.retrieve(chargebee_subscription).request(
     function(error,result){
       if(error){
        //handle error        
       callback(error)
    }else{
        callback(null,result);
     }
    });
   } 

This way console.log will get the right data from the function.

Checking Javascipt Variables

A good way to check if the variable exists (or undefined)

if (typeof addContext === 'defined') {
   console.log(addContext);
}