Files
qtpromise/docs/qtpromise/qpromise/then.md
Simon Brunel 18739bd8e0 New documentation based on GitBook CLI
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
2018-02-11 19:02:14 +01:00

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 as input.

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 as onFulfilled. That also means if onFulfilled is nullptr, onRejected must return the same type as the input 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.