使函数等待参数解析

问题描述 投票:0回答:1

是否已经有类似以下功能的东西。

/**
 * ex.
 * const ret = await asyncify(Math.max)(arg1, arg2);
 */
asyncify(func) {
  return async (...inputs) => {
    // wait for all inputs being resolved
    const inputsResolved = await Promise.all(inputs);
    return await func(...inputsResolved);
  };
}

/**
 * ex.
 * const ret = await execute(Math.max, arg1, arg2);
 */
async execute(func, ...inputs) {
  // wait for all inputs being resolved
  const inputsResolved = await Promise.all(inputs);
  return await func(...inputsResolved);
}

通过这些函数(一个或另一个),我可以异步执行一些操作,而无需复杂的代码结构,以确保任务以正确的顺序执行并最大程度地并行。

// Task A and B can run in parallel
const retA = asyncTaskA(payloadA);
const retB = asyncTaskB(payloadB);

// Task C and D depend on A and B, but they can run in parallel as well.
const retC = asyncify(
  (payloadC1, payloadC2) => {
    asyncTaskC(payloadC1.someField, payloadC2.otherField);
  }
)(retA, retB);
const retD = asyncify(asyncTaskD)(retA, retB);
// Task A and B can run in parallel
const retA = asyncTaskA(payloadA);
const retB = asyncTaskB(payloadB);

// Task C and D depend on A and B, but they can run in parallel as well.
const retC = execute(
  (payloadC1, payloadC2) => {
    asyncTaskC(payloadC1.someField, payloadC2.otherField);
  },
  retA,
  retB
);
const retD = execute(asyncTaskD, retA, retB);

如果没有,是否值得添加到 Promise 中,类似于

Promise.all

const retC = Promise.asyncify(asyncTaskD)(retA, retB));

更新:添加更复杂的示例:

/**
 * A -> B
 * B -> C
 * A -> D
 * B,D -> E
 * C,E -> F
 */
async function aComplexWorkflow() {
  const A = Lib.execute(asyncTaskA);
  const B = Lib.execute(asyncTaskB, A);
  const C = Lib.execute(asyncTaskC, B);
  const D = Lib.execute(asyncTaskD, A);
  const E = Lib.execute(asyncTaskE, B, D);
  const F = Lib.execute(asyncTaskF, C, E);
  return F;
}
asynchronous async-await promise monads
1个回答
1
投票

是否已经有类似以下功能的东西。

没有。

然后我可以异步执行一些操作,而无需复杂的代码结构

我认为你的代码并不比编写代码简单

const [retA, retB] = await Promise.all([
  asyncTaskA(payloadA),
  asyncTaskB(payloadB),
]);

const retC = asyncTaskC(retA, retB);
const retD = asyncTaskD(id, forecast.result);

我什至认为使用

execute
/
asyncify
比仅仅内联它们更难理解。

是否值得添加到 Promise 中,类似于

Promise.all

不 - 并且请不要修改内置函数

© www.soinside.com 2019 - 2024. All rights reserved.