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

Awaiting QtPromises of different type #23

Open
milianw opened this issue Feb 13, 2019 · 1 comment
Open

Awaiting QtPromises of different type #23

milianw opened this issue Feb 13, 2019 · 1 comment

Comments

@milianw
Copy link

milianw commented Feb 13, 2019

Hey there,

would it be possible to add API or an example on how to wrap promises of different types? E.g. to handle a scenario such as:

  • do A returning a_t
  • do B returning b_t
  • await for A and B then do C taking a_t and b_t.

Ideally something like this:

auto a = qPromise(QtConcurrent::run([](){return QStringLiteral("foo");}));
auto b = qPromise(QtConcurrent::run([](){return 42;}));
qPromiseAll(a, b).then([](const QString &str, int num) {});

I believe one could handle this manually by building a promise that stores a tuple of return args (here QString and int) as well as a counter to check how many of the child promises have been fulfilled. Then when a child promise is fulfilled store its return type and decrement the counter, and if that reaches zero resolve the parent promise? And if any child promise gets rejected, also reject the parent promise?

@milianw
Copy link
Author

milianw commented Feb 13, 2019

Interesting, this seems to work fine for two args at least:


template<typename T1, typename T2>
QPromise<QPair<T1, T2>> qAwaitAll(const QPromise<T1>& p1, const QPromise<T2>& p2)
{
    return p1.then([p2](const T1& arg1) {
        return p2.then([arg1](const T2& arg2) {
            return QPromise<QPair<T1, T2>>([arg1, arg2](const QPromiseResolve<QPair<T1, T2>>& resolve){
                resolve(qMakePair(arg1, arg2));
            });
        });
    });
}

...

    auto a = qPromise(QtConcurrent::run([](){return QStringLiteral("foo");}));
    auto b = qPromise(QtConcurrent::run([](){return 42;}));
    qAwaitAll(a, b).then([](const QPair<QString, int>& data) { qDebug() << data;});

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

No branches or pull requests

2 participants