QtConcurrent

QtPromise integrates with QtConcurrent to make easy chaining QFuture with QPromise.

Convert

Converting QFuture<T> to QPromise<T> is done using the qPromise helper:

QFuture<int> future = QtConcurrent::run([]() {
    // {...}
    return 42;
});

QPromise<int> promise = qPromise(future);

or simply:

auto promise = qPromise(QtConcurrent::run([]() {
    // {...}
}));

Chain

Returning a QFuture<T> in then or fail automatically translate to QPromise<T>:

QPromise<int> input = ...
auto output = input.then([](int res) {
    return QtConcurrent::run([]() {
        // {...}
        return QString("42");
    });
});

// output type: QPromise<QString>
output.then([](const QString& res) {
    // {...}
});

The output promise is resolved when the QFuture is finished.

Error

Exceptions thrown from a QtConcurrent thread reject the associated promise with the exception as the reason. Note that if you throw an exception that is not a subclass of QException, the promise with be rejected with QUnhandledException (this restriction only applies to exceptions thrown from a QtConcurrent thread, read more).

QPromise<int> promise = ...
promise.then([](int res) {
    return QtConcurrent::run([]() {
        // {...}

        if (!success) {
            throw CustomException();
        }

        return QString("42");
    });
}).fail(const CustomException& err) {
    // {...}
});
Last Updated: 9/9/2018, 8:55:07 AM