djinni icon indicating copy to clipboard operation
djinni copied to clipboard

[Future] Unwrap nested futures with .then()

Open bkotsopoulossc opened this issue 2 years ago • 0 comments

Right now in C++ we have the ability to chain up a function to run after a future completes.

Future<int> someAsyncFunc() {
  Promise<int> promise;
  auto future = promise.getFuture();

  std::async(std::launch_async, [p = std::move(promise)]() {
    std::this_thread::sleep_for (std::chrono::seconds(1));
    p.setValue(5);
  })

  return future;
}

Future<int> processAsyncValue() {
  return someAsyncFunc().then([](auto future){
    auto value = future.get();
    return value * 2;
  })
}

But currently the then() operation does not support handlers that themselves return a future. This would be useful to have so you can set up an async chain of functions to run, and the future of the handler gets "unwrapper". In Javascript, the then() operator takes a function that either returns the value type, or a Promise of the value type. They become interchangeable in a function chain:

async function doubleAsync(input: number): Promise<number> {
    return new Promise((resolve, _reject) => {
        setTimeout(() => {
            resolve(input * 2);
        }, 10);
    });
}

function doubleSync(x: number): number { return x * 2};

doubleAsync(4).then(doubleSync).then(doubleAsync).then(a => console.log(a));

Can we support this in C++, so that the handler passed into .then() can return a value of type T, or a Future<T>?

CC @LiFengSC

bkotsopoulossc avatar Dec 02 '22 21:12 bkotsopoulossc