Ballerina Swan Lake - 如何交替等待一组动态的 Ballerina 未来值?

Ballerina Swan Lake - How to alternatively wait on a dynamic set of Ballerina future values?

我需要编写一个 ballerina util 函数,该函数可以交替等待给定的一组期货和 return 结果,其中未来值的数量可能会有所不同,如下所示 源码.

function getWaitResult(future[] futures) returns any|error {
    return wait futures[0] | futures[1] | ... | futures[n];
}

使用 Ballerina Swan Lake 版本实现相同功能的最佳方法是什么?

由于您必须静态地提供每个未来的参考,我建议您生成更多的站点,结合备用等待操作。

import ballerina/lang.runtime;
import ballerina/io;
import ballerina/random;
function waitHelper(future<any>[] fs) returns any|error {
    match fs {
        var [f] => {
            return wait f;
        }
        var [f, x] => {
            return wait f | x;
        }
        var [f, x, y] => {
            return wait f | x | y;
        }
        var [f, x, y, ...r] => {
            var rest = start waitHelper(r);
            return wait f | x | y | rest;
        }
    }
}
function foo() returns int {
    int r = checkpanic random:createIntInRange(10, 200);
    io:println("waiting (ms)... ", r);
    runtime:sleep((<decimal>r)/1000);
    return r;
}
public function main() {
    future<int>[] f = [];
    foreach int i in 0...9 {
        var r = start foo();
        f.push(r);
    }
    any|error got = waitHelper(f);
    io:println("Got: ", got);
}