Implement QtPromise::attempt(functor, args...)

Add a new helper that calls functor immediately and returns a promise fulfilled with the value returned by functor. Any synchronous exceptions will be turned into rejections on the returned promise. This is a convenient method that can be used instead of handling both synchronous and asynchronous exception flows.

Also simplify PromiseDispatch which now calls the functor with a variable number of arguments (including none).
This commit is contained in:
Simon Brunel
2018-05-21 21:33:05 +02:00
parent 4fa7a37750
commit f610826ef0
8 changed files with 200 additions and 55 deletions

View File

@ -22,5 +22,6 @@
* [::resolve (static)](qtpromise/qpromise/resolve.md)
* [qPromise](qtpromise/helpers/qpromise.md)
* [qPromiseAll](qtpromise/helpers/qpromiseall.md)
* [QtPromise::attempt](qtpromise/helpers/attempt.md)
* [QtPromise::filter](qtpromise/helpers/filter.md)
* [QtPromise::map](qtpromise/helpers/map.md)

View File

@ -27,5 +27,6 @@
* [`qPromise`](helpers/qpromise.md)
* [`qPromiseAll`](helpers/qpromiseall.md)
* [`QtPromise::attempt`](helpers/attempt.md)
* [`QtPromise::filter`](helpers/filter.md)
* [`QtPromise::map`](helpers/map.md)

View File

@ -0,0 +1,41 @@
## `QtPromise::attempt`
```cpp
QtPromise::attempt(Functor functor, Args...) -> QPromise<R>
// With:
// - Functor: Function(Args...) -> R | QPromise<R>
```
Calls `functor` immediately and returns a promise fulfilled with the value returned by
`functor`. Any synchronous exceptions will be turned into rejections on the returned
promise. This is a convenient method that can be used instead of handling both synchronous
and asynchronous exception flows.
The type `R` of the `output` promise depends on the type returned by the `functor` function.
If `functor` returns a promise (or `QFuture`), the `output` promise is delayed and will be
resolved by the returned promise.
```cpp
QPromise<QByteArray> download(const QUrl& url);
QPromise<QByteArray> process(const QUrl& url)
{
return QtPromise::attempt([&]() {
if (!url.isValid()) {
throw InvalidUrlException();
}
return download(url);
}
}
auto output = process(url);
// 'output' type: QPromise<QByteArray>
output.then([](const QByteArray& res) {
// {...}
}).fail([](const InvalidUrlException& err) {
// {...}
});
```