我正在尝试实现 CombineFunction
// Sync tasks
function f1(args,function() { /* Does something */ });
function f2(args,function() { /* Does something */ });
function f3(args,function() { /* Does something */ });
const op = combineFxn([f1, f2,f3]);
// After combineFxn is combined, we need to invoke each of the
// tasks function with 'test' arguments.
op('demo', function() {
//cb
});
问题陈述:
Implement combineFxn.
- This should return a function if invoked with
test
as an argument should invoke all the three function(s):f1
,f2
andf3
with arguments.The final response from
operation
should only be returned after all the tasks are finishedAll tasks are synchronous or async tasks.
最佳答案
如果我对你的问题的理解正确,你想将任务组合在一起并返回一个组合任务。
这是一种适用于异步任务的方法。您也可以使用它来运行同步任务,但您需要使用 then
来获取结果,因为所有内容都包含在 Promise 中:
const combineTasks = (...tasks) => (...args) =>
tasks.reduce(async (previous, task) => {
const result = await previous;
return task(result);
}, Promise.resolve(...args));
const delay = ms => new Promise(res => setTimeout(res, ms));
const f1 = x => x + 1;
const f2 = x => x * 2;
const f1Async = async (x) => {
console.log(x);
await delay(300);
return x + 1;
};
const f2Async = async (x) => {
console.log(x);
await delay(300);
return x * 2;
};
// Asynchronous task
const taskAsync = combineTasks(f1Async, f2Async, f1Async);
taskAsync(1).then(r => console.log(r));
// Synchronous task
const task = combineTasks(f1, f2, f1);
task(100).then(r => console.log(r));
如果你想要一个同步的 API,你可以这样做:
const combineTasks = (...tasks) => args =>
tasks.reduce((prev, task) => task(prev), args);
const f1 = x => { console.log(x); return x + 1; };
const f2 = x => { console.log(x); return x * 2; };
const task = combineTasks(f1, f2, f1);
console.log(task(10));
关于javascript - 实现组合函数和返回结果的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081064/