具有异步库的参数的模板功能

时间:2018-05-25 18:42:47

标签: javascript callback async.js

我正在尝试编写一个包装器,以便我可以删除不同文件之间的重复代码。我有几个工人,它们列出了参数和回调列表。如果某些条件为真,则调用其他服务并使用结果调用回调,否则使用空数组调用回调。

(sort (copy-list list) #'< :key #'cdr)

这些工人实际上是从收集者那里调用的,如下所示。我正在使用Worker1.js ~~~~~~~~~ export function get(shouldCall, param11, param12, callback) { if(shouldCall) { someService.get(param11, param12, callback); } else { callback(null, []); } } Worker2.js ~~~~~~~~ export function get(shouldCall, param21, callback) { if(shouldCall) { someOtherService.get(param21, callback); } else { callback(null, []); } } 库。

async

我希望从收集器中调用这个模板:

collector.js
   ~~~~~~~~~~~~
    import async from 'async';

    function doSomething(callback) {
      async.auto({
        worker1Result: async.apply(worker1.get, true, 'abc', 'xyz'),
        worker2Result: async.apply(worker2.get, true, 'mno', 'uvw')
      }, (err, result) => {
        callback(err, result);
      })
    }

我尝试过类似下面的模板。问题是我没有看到将参数传递给服务调用的方法。有什么建议吗?

function doSomething(callback) {
  const serviceOneCall = async.apply(someService.get, param11, param12);
  const serviceTwoCall = async.apply(someService.get, param11, param12);

  async.auto({
    worker1Result: async.apply(template.execute, true, serviceOneCall),
    worker2Result: async.apply(template.execute, true, serviceTwoCall)
  }, (err, result) => {
    callback(err, result);
  })
}

1 个答案:

答案 0 :(得分:0)

execute函数提供额外参数,然后使用解构语法或apply方法:

&#13;
&#13;
function execute1(shouldCall, serviceToCall, callback, ...args) {
  if (shouldCall) {
    return serviceToCall(...args);              
  }

  return [];
}
  
function execute2(shouldCall, serviceToCall, callback) {
  if (shouldCall) {
    return serviceToCall.apply(undefined, Array.prototype.slice.call(arguments, 3));              
  }

  return [];
}
  
execute1(true, console.log.bind(console), null, 1, 2, 3);
execute2(true, console.log.bind(console), null, 4, 5, 6, 7);
&#13;
&#13;
&#13;