Differential D18758 Diff 58398 kdevplatform/3rdparty/qtpromise/qtpromise-0.5.0/docs/qtpromise/qtconcurrent.md
Changeset View
Changeset View
Standalone View
Standalone View
kdevplatform/3rdparty/qtpromise/qtpromise-0.5.0/docs/qtpromise/qtconcurrent.md
- This file was added.
1 | # Qt Concurrent | ||||
---|---|---|---|---|---|
2 | | ||||
3 | QtPromise integrates with [QtConcurrent](https://doc.qt.io/qt-5/qtconcurrent-index.html) to make easy chaining QFuture with QPromise. | ||||
4 | | ||||
5 | ## <a name="qtconcurrent-convert"></a> Convert | ||||
6 | | ||||
7 | Converting `QFuture<T>` to `QPromise<T>` is done using the [`QtPromise::resolve`](helpers/resolve.md) helper: | ||||
8 | | ||||
9 | ```cpp | ||||
10 | QFuture<int> future = QtConcurrent::run([]() { | ||||
11 | // {...} | ||||
12 | return 42; | ||||
13 | }); | ||||
14 | | ||||
15 | QPromise<int> promise = QtPromise::resolve(future); | ||||
16 | ``` | ||||
17 | | ||||
18 | or simply: | ||||
19 | | ||||
20 | ```cpp | ||||
21 | auto promise = QtPromise::resolve(QtConcurrent::run([]() { | ||||
22 | // {...} | ||||
23 | })); | ||||
24 | ``` | ||||
25 | | ||||
26 | ## Chain | ||||
27 | | ||||
28 | Returning a `QFuture<T>` in [`then`](qpromise/then.md) or [`fail`](qpromise/fail.md) automatically translate to `QPromise<T>`: | ||||
29 | | ||||
30 | ```cpp | ||||
31 | QPromise<int> input = ... | ||||
32 | auto output = input.then([](int res) { | ||||
33 | return QtConcurrent::run([]() { | ||||
34 | // {...} | ||||
35 | return QString("42"); | ||||
36 | }); | ||||
37 | }); | ||||
38 | | ||||
39 | // output type: QPromise<QString> | ||||
40 | output.then([](const QString& res) { | ||||
41 | // {...} | ||||
42 | }); | ||||
43 | ``` | ||||
44 | | ||||
45 | The `output` promise is resolved when the `QFuture` is [finished](https://doc.qt.io/qt-5/qfuture.html#isFinished). | ||||
46 | | ||||
47 | ## Error | ||||
48 | | ||||
49 | 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 will be rejected with [`QUnhandledException`](https://doc.qt.io/qt-5/qunhandledexception.html#details) (this restriction only applies to exceptions thrown from a QtConcurrent thread, [read more](https://doc.qt.io/qt-5/qexception.html#details)). | ||||
50 | | ||||
51 | ```cpp | ||||
52 | QPromise<int> promise = ... | ||||
53 | promise.then([](int res) { | ||||
54 | return QtConcurrent::run([]() { | ||||
55 | // {...} | ||||
56 | | ||||
57 | if (!success) { | ||||
58 | throw CustomException(); | ||||
59 | } | ||||
60 | | ||||
61 | return QString("42"); | ||||
62 | }); | ||||
63 | }).fail(const CustomException& err) { | ||||
64 | // {...} | ||||
65 | }); | ||||
66 | ``` |