0

我正在寻找一种将功能链接在一起的方法,类似于lodashoverSomeflow在 lodash 中。

这是写出的可比函数。

const e = async ({planGroups, uuid, name, user, organization}) => {
  const a = this.getPlanGroupByUuid({ planGroups, uuid })
  if (a) return a
  const b = this.getPlanGroupByName({ planGroups, name })
  if (b) return b
  const c = await this.createPlanGroup({ name, user, organization })
  return c
}

e({planGroups, uuid, name, user, organization})

这将是作曲版本。

const x = await _.overSome(this.getPlanGroupByUuid, this.getPlanGroupByName, this.createPlanGroup)

x({planGroups, uuid, name, user, organization})

这个想法是该函数返回带有truthy值的第一个函数。

仅在 lodash 内这可能吗?是否有更好的带有打字稿支持的组合函数库?

4

1 回答 1

1

您可以使用ramda. 例子:

const composeWhileNotNil = R.composeWith(async (f, res) => {
  const value = await res;
  return R.isNil(value) ? value : f(value)
});


const getA = x => x * 2
const getB = x => Promise.resolve(x * 3)
const getC = x => x * 10


async function run(){
  const result = await composeWhileNotNil([getC, getB, getA])(1);
  console.log("result:", result); // result: 60
}

run();

如果您更喜欢从左到右的组合,可以使用pipeWith

工作示例:https ://repl.it/repls/TemptingAridGlitch

于 2019-09-07T00:20:24.977 回答