Daniel
Daniel

Reputation: 199

Calling a function with default parameters which also has a callback

Consider the example code:

function makeRequest(endpoint, form = {}, qs = {}, callback) {
  const exampleObject = {
    endpoint,
    form,
    qs,
  };
  callback(exampleObject);
}

makeRequest('/example', { foo: 'string' }, { bar: 'string' }, (exampleObject) => {
  console.log(exampleObject);
});

In the above example the following object would be logged on the console:

{ endpoint: '/example',
  form: { foo: 'string' },
  qs: { bar: 'string' } }

How can I use the defaults in makeRequest and still utilize the callback? For instance, the following fails:

makeRequest('/example', (exampleObject) => {
  console.log(exampleObject);
});

Output:

/Users/daniel/example.js:13
  callback(exampleObject);
  ^

TypeError: callback is not a function
    at makeRequest (example.js:7:3)
    at Object.<anonymous> (example.js:10:1)
    at Module._compile (module.js:409:26)
    at loader (/usr/local/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:148:5)
    at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:158:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at /usr/local/lib/node_modules/babel-cli/lib/_babel-node.js:160:24
    at Object.<anonymous> (/usr/local/lib/node_modules/babel-cli/lib/_babel-node.js:161:7)

This makes sense considering I am sending only one parameter. I am wondering how I can call makeRequest while taking advantage of the default parameters and still get the callback. Will I always have to pass three parameters if a callback exists? Is there some other way to go about this so I have the option of only using the 2nd and 3rd parameters if needed and always get exampleObject in the callback?

Upvotes: 1

Views: 55

Answers (2)

Andreas
Andreas

Reputation: 21881

How about destructuring?

function makeRequest({ endpoint, form = {}, qs = {}, callback = () => {} }) {
  const exampleObject = {
    endpoint,
    form,
    qs,
  };

  callback(exampleObject);
}

makeRequest({
  endpoint: '/example',
  callback: (x) => console.log(x)
});

Upvotes: 4

user2033671
user2033671

Reputation:

Passing undefined will use the default parameter

makeRequest('/example',undefined,undefined,(exampleObject) => {
  console.log(exampleObject);
});

Upvotes: 3

Related Questions