mirror of
https://github.com/simonbrunel/qtpromise.git
synced 2025-07-04 08:15:25 +08:00
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:
@ -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)
|
||||
|
@ -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)
|
||||
|
41
docs/qtpromise/helpers/attempt.md
Normal file
41
docs/qtpromise/helpers/attempt.md
Normal 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) {
|
||||
// {...}
|
||||
});
|
||||
```
|
Reference in New Issue
Block a user