Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
bkotsopoulossc opened this issue Dec 2, 2022 · 0 comments
Open

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

bkotsopoulossc opened this issue Dec 2, 2022 · 0 comments

Comments

@bkotsopoulossc
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant