gpt4 book ai didi

javascript - 使用默认参数调用也有回调的函数

转载 作者:行者123 更新时间:2023-11-30 07:34:21 25 4
gpt4 key购买 nike

考虑示例代码:

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

最佳答案

destructuring怎么样? ?

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

callback(exampleObject);
}

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

关于javascript - 使用默认参数调用也有回调的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com