8000 [Future] Unwrap nested futures with .then() · Issue #121 · Snapchat/djinni · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
[Future] Unwrap nested futures with .then() #121
Open
@bkotsopoulossc

Description

@bkotsopoulossc

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0