Split the root README.md in multiple Markdown files (in the `docs/` folder) to make easier reading, editing and extending the documentation. An online version is also available on netlify (https://qtpromise.netlify.com). Building it requires Node.js installed, then: - npm install -g gitbook-cli - gitbook install ./ - gitbook build . dist/docs
2.3 KiB
QPromise<T>::then
QPromise<T>::then(Function onFulfilled, Function onRejected) -> QPromise<R>
QPromise<T>::then(Function onFulfilled) -> QPromise<R>
See Promises/A+ .then
for details.
QPromise<int> input = ...
auto output = input.then([](int res) {
// called with the 'input' result if fulfilled
}, [](const ReasonType& reason) {
// called with the 'input' reason if rejected
// see QPromise<T>::fail for details
});
Note
:
onRejected
handler is optional,output
will be rejected with the same reason asinput
.
Note
: it's recommended to use the
fail
shorthand to handle errors.
The type <R>
of the output
promise depends on the return type of the onFulfilled
handler:
QPromise<int> input = {...}
auto output = input.then([](int res) {
return QString::number(res); // -> QPromise<QString>
});
// output type: QPromise<QString>
output.then([](const QString& res) {
// {...}
});
Note
: only
onFulfilled
can change the promise type,onRejected
must return the same type asonFulfilled
. That also means ifonFulfilled
isnullptr
,onRejected
must return the same type as theinput
promise.
QPromise<int> input = ...
auto output = input.then([](int res) {
return res + 4;
}, [](const ReasonType& reason) {
return -1;
});
If onFulfilled
doesn't return any value, the output
type is QPromise<void>
:
QPromise<int> input = ...
auto output = input.then([](int res) {
// {...}
});
// output type: QPromise<void>
output.then([]() {
// `QPromise<void>` `onFulfilled` handler has no argument
});
You can also decide to skip the promise result by omitting the handler argument:
QPromise<int> input = {...}
auto output = input.then([]( /* skip int result */ ) {
// {...}
});
The output
promise can be rejected by throwing an exception in either onFulfilled
or onRejected
:
QPromise<int> input = {...}
auto output = input.then([](int res) {
if (res == -1) {
throw ReasonType();
} else {
return res;
}
});
// output.isRejected() is true
If an handler returns a promise (or QFuture), the output
promise is delayed and will be resolved by the returned promise.