node.js - How to support 2 types of callback in Javascript -


in intercom-client github see code:

client.users.list(function (d) {   // d response server });  // or  client.users.list(function (err, d) {   // err error response object, or null   // d successful response object, or null }); 

my question is: how intercom know if pass funcrtion(err,d) or function(data).

i check source code , found use bluebird library. how bluebird it?

i want function same.

in other words:

function myfunction(data,callback){   if (callbacklistentoerrargument(callback))         callback(null,data)    else        callback(data)  } 

how implement callbacklistentoerrargument function?

one can inspect .length property on function getting passed. .length property number of arguments defined function.

function haserrorargument(callback) {   if (callback.length < 2) { return false; } // has 1 or 0.   else return true; // has 2 or more } // yes, know can reduced 1 line. sue me. 

please note: bad practice. should provide uniform signature callbacks accept. (err, data) => {} signature follow.

or better, have list() function return promise object: (promises natively supported in browsers. check compatibility before use, or use polyfill or library).

client.users.list()   .then(listofusers => {     // use data here   })   .catch(err => {     // handle errors here   }); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -