#include "promise_examples.h" #include "promise.h" #include #include #include namespace LtsUtils { void PromiseExample1_Class::doSomethingAsync1() { QTimer::singleShot(200, this, [this]() { emit signalDone1(true); }); } void PromiseExample1_Class::doSomethingAsync2() { QTimer::singleShot(450, this, [this]() { emit signalDone2(true, 1234); }); } PromiseExample1::PromiseExample1(QObject *parent) : QObject(parent) , m_success(false) { auto func = [this](ResultFunction resolve , ResultFunction reject ) { PromiseExample1_Class *c = new PromiseExample1_Class(this); connect(c, &PromiseExample1_Class::signalDone1, this, [this, c, resolve, reject](bool didThisWork) { if (!didThisWork) { reject(QStringLiteral("First Action did not succeed")); return; } else { connect(c, &PromiseExample1_Class::signalDone2, this, [resolve, reject](bool didThisWork, int someNumberThatReturns) { if (didThisWork) resolve(someNumberThatReturns); else reject(QStringLiteral("Second Action did not succeed")); }); c->doSomethingAsync2(); } }); c->doSomethingAsync1(); }; Promise *p = new Promise(func, this); p->resolved([this](const QVariant &value) { qDebug() << "example1 promise succeeded! 'someNumberThatReturns' was" << value; m_success = true; }).rejected([](const QVariant &value) { qDebug() << "example1 promise failed.." << value; }); } PromiseExample2::PromiseExample2(QObject *parent) : QObject(parent) , m_success(false) { Promise *p = new Promise([](ResultFunction , ResultFunction ) { }, this); p->setTimeout(1000); p->resolved([](const QVariant &) { QFAIL("This test case's promise should never resolve"); }); p->rejected([this](const QVariant &val) { QVERIFY2(val == QStringLiteral("timeout"), "Promise didn't reject with string \"timeout\""); qDebug() << "Promise rejected as expected"; m_success = true; }); } PromiseExample3::PromiseExample3(QObject *parent) : QObject(parent) , m_success(true) , m_alreadyRejected(false) { Promise *p = new Promise([](ResultFunction , ResultFunction reject) { reject(QString()); }, this); p->setTimeout(1000); p->resolved([](const QVariant &) { QFAIL("This test case's promise should never resolve"); }); p->rejected([this](const QVariant &val) { qDebug() << "rejected with val" << val; QVERIFY2(val == QString(), "Promise didn't reject with an expected empty string."); QVERIFY2(!m_alreadyRejected, "Promise rejected more than once"); m_alreadyRejected = true; qDebug() << "Promise rejected as expected"; }); } }