How nice to do asynchronous network requests in Qt

I want to make a series of network requests (in Qt) in which the details of one request depend on the result of the latter. Currently my code is as follows:

QNetworkReply *reply = m->get(QNetworkRequest(QUrl("http://qt-project.org")));
    reply->connect(reply,&QNetworkReply::finished,[=](){
        //Do something with reply, calculate a value for the next request
        QNetworkReply *reply2 = m->get(QNetworkRequest(QUrl("http://www.google.de")));
        reply->deleteLater();
        reply2->connect(reply2,&QNetworkReply::finished,[=](){
            //Do something with reply2, calculate a value for the next request
            QNetworkReply *reply3 = m->get(QNetworkRequest(QUrl("http://amazon.de")));
            reply2->deleteLater();
            reply3->connect(reply3,&QNetworkReply::finished,[=](){
                //...
            });
        });
    });

While this works, I see two problems:

  • The code gets really ugly when I want to fulfill more requests.
  • How do I handle errors? I can not use throw.

So, I'm looking for a way to better structure this code. I thought of the following options:

(1) Use lock requests, you can simply write (pseudo code!):

try {
    ResultType res1 = blockingRequest("http://qt-project.org");
    // Doe something with res1
    ResultType res2 = blockingRequest("http://www.google.com");
    // Doe something with res2
    ResultType res3 = blockingRequest("http://amazon.de");
    // Doe something with res3
catch(...) {
    // ...
}

This code must be run in a separate thread. I read that locking requests are hard to do in Qt, and I would rather stick with the standard Qt way of doing something.

(2) - . "do" haskell. Haxe MonadSurprise. Haxe, :

MonadSurprise.dO({
    res1 <= request("http://qt-project.org");
    res2 <= request("http://www.google.de");
    res3 <= request("http://amazon.de");
});

MonadSurprise.dO - , , ( ). , .

, - ++/qt.

+4

Source: https://habr.com/ru/post/1618783/


All Articles