我试图在第一次解决时运行第二个查询,如下所示:
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不是一个函数,而对1.json和2.json的请求工作正常fn2似乎没有收到fn3作为参数。你能解释它是如何工作的吗?
你似乎认为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();