Snapchat / djinni

A tool for generating cross-language type declarations and interface bindings. Djinni's new home is in the Snapchat org.
Apache License 2.0
179 stars 50 forks source link

[Future] Unwrap nested futures with .then() #121

Open bkotsopoulossc opened 1 year ago

bkotsopoulossc commented 1 year ago

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