javascript - 实现组合函数和返回结果的问题

标签 javascript

我正在尝试实现 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 and f3 with arguments.
  • The final response from operation should only be returned after all the tasks are finished

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

相关文章:

Javascript defineGetter

javascript - asp.net usercontrol 不会在 updatepanel 中触发 javascript

javascript - JS cancelAnimationFrame 语法

javascript - 当指令更新相同的范围变量时, Angular 父范围不会更新

javascript - 使用 v8 和过滤器/查找比较两个对象数组的高效方法

javascript - 我正在尝试在单击按钮后清除输入字段

javascript - 用图像替换普通文件上传输入

javascript - 删除选择框reactJS中出现的编辑和删除按钮

javascript - 所有外部 js 和 css 文件上的 Gulp 和浏览器同步 404

javascript - 未找到捆绑文件