gpt4 book ai didi

javascript - 将参数绑定(bind)到函数javascript

转载 作者:行者123 更新时间:2023-11-29 20:41:59 26 4
gpt4 key购买 nike

当第一个查询像这样解决时,我正在尝试运行第二个查询:

const fn1 = secondQuery => $.get('1.json', data => secondQuery());
const fn2 = secondQuery => $.get('2.json', data => secondQuery());
const fn3 = secondQuery => $.get('3.json', data => secondQuery());
const fn4 = secondQuery => $.get('4.json', data => secondQuery());

const queries = [fn1, fn2, fn3, fn4];

const queriesWithArgs = queries.map((queryFn, index, arr) => {
const nextQuery = arr[index + 1];

if (!nextQuery) {
return
}

return queryFn.bind(queryFn, nextQuery);
});

queriesWithArgs[0]();

但仍然收到错误 TypeError: secondQuery is not a function, while requests to 1.json and 2.json works fine fn2 seems to not receive fn3 as argument.你能解释一下它是如何工作的吗?

最佳答案

您似乎认为 arr 参数指的是 queriesWithArgs 数组,因此您可以从那里获取 nextQuery。它不是,它指的是原始 queries 数组,您正在调用那些 nextQuery 函数而无需进一步的参数。

相反,此处使用的正确工具是 reduceRight ,而不是 map,其中 nextQuery 累加器确实会引用之前的结果(或初始值,这里是 last 回调):

const queries = [fn1, fn2, fn3, fn4];

const run = queries.reduceRight((nextQuery, queryFn) => {
return queryFn.bind(null, nextQuery);
}, function last() {
console.log("done");
});

run();

关于javascript - 将参数绑定(bind)到函数javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195826/

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