使用默认参数调用函数,该参数也具有回调函数

时间:2016-07-28 19:00:39

标签: javascript ecmascript-6

考虑示例代码:

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

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

在上面的示例中,将在控制台上记录以下对象:

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

如何使用makeRequest中的默认值并仍然使用回调?例如,以下操作失败:

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

输出:

/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)

考虑到我只发送一个参数,这是有道理的。我想知道如何在利用默认参数的同时调用makeRequest并仍然获得回调。如果存在回调,我是否总是必须传递三个参数?还有其他方法可以解决这个问题,所以我可以选择只在需要时使用第二个和第三个参数,并且总是在回调中获得exampleObject吗?

2 个答案:

答案 0 :(得分:4)

destructuring怎么样?

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

  callback(exampleObject);
}

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

答案 1 :(得分:3)

传递undefined将使用default parameter

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