有没有一种方法可以“分支”和合并两个期货,同时保持单级通话链?

时间:2018-08-20 14:43:22

标签: java java-8 completable-future

我有一连串这样的电话:

HOST = " 192.168.15.101"
user = input("Enter your device username: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("enable\n")
tn.write("cisco\n")
tn.write("conf t\n")
tn.write("interface loop 1\n")
tn.write("ip address 1.1.1.1 255.255.255.255\n")
tn.write("interface loop 2\n")
tn.write("ip address 1.1.1.2 255.255.255.255\n")
tn.write("interface loop 3\n")
tn.write("ip address 1.1.1.3 255.255.255.255\n")
tn.write("interface loop 4\n")
tn.write("ip address 1.1.1.4 255.255.255.255\n")
tn.write("end\n")
tn.write("exit\n")

print(tn.read_all())

当然可以简化。现在,我需要添加另一个呼叫。

return doFirst.thenCompose(a -> {
  return doSecond(a);
}).thenCompose(b -> {
  return doThird(b);
}).thenCompose(c -> {
  return doFourth(c);
});

这可能与return doWithThird(b); 同时发生,所以我看到的一种方式是嵌套doThird

thenCombine

我只是很好奇,有没有办法做到这一点而无需嵌套? 继续进行单级通话吗?

1 个答案:

答案 0 :(得分:0)

如果您接受使用局部变量,则可以避免lambda表达式/“ 调用链”的嵌套:

function createSetting() {
    Office.context.document.settings.set("Foo", "bar");
    Office.context.document.settings.saveAsync();
}

function readSetting() {
    console.log(Office.context.document.settings.get("Foo"));
}

这也应该有助于使代码更具可读性,因为带有长lambda的长调用链往往会失去可读性。

当然,如果您想减少 chains 的数量,仍然可以内联second = doFirst.thenCompose(a -> { return doSecond(a); }); third = second.thenCompose(b -> doThird(b)); otherThird = second.thenCompose(b -> doWithThird(b)); return third.thenCombine(otherThird, (b1, b2) -> { return doSomethingWithTheThirds(b1, b2); }); }).thenCompose(c -> { return doFourth(c); }); third