104 lines
1.7 KiB
C++
Executable File
104 lines
1.7 KiB
C++
Executable File
|
|
|
|
|
|
#include "promise.h"
|
|
|
|
#include <QTimer>
|
|
|
|
namespace LtsUtils
|
|
{
|
|
|
|
Promise::Promise(const std::function<void(ResultFunction resolve, ResultFunction reject)> &function, QObject *parent)
|
|
: QObject(parent)
|
|
, m_functionAlreadySet(false)
|
|
, m_timeout(new QTimer(this))
|
|
, m_resultSet(false)
|
|
, m_timeoutSet(false)
|
|
{
|
|
m_timeout->setSingleShot(true);
|
|
connect(m_timeout, &QTimer::timeout,
|
|
this, &Promise::slotTimeout);
|
|
setFunction(function);
|
|
}
|
|
|
|
|
|
void Promise::setFunction(const std::function<void(ResultFunction resolve, ResultFunction reject)> &function)
|
|
{
|
|
if (!function || m_functionAlreadySet)
|
|
return;
|
|
|
|
m_functionAlreadySet = true;
|
|
|
|
if (m_timeoutSet)
|
|
m_timeout->start();
|
|
|
|
|
|
QTimer::singleShot(0, this, [this, function]()
|
|
{
|
|
|
|
function([this](const QVariant &value)
|
|
{
|
|
resolve(value);
|
|
}, [this](const QVariant &value)
|
|
{
|
|
|
|
reject(value);
|
|
});
|
|
});
|
|
}
|
|
|
|
|
|
void Promise::setTimeout(int interval)
|
|
{
|
|
m_timeout->stop();
|
|
m_timeout->setInterval(interval);
|
|
m_timeoutSet = (interval != 0);
|
|
|
|
if (interval != 0 && m_functionAlreadySet)
|
|
m_timeout->start();
|
|
}
|
|
|
|
|
|
void Promise::slotTimeout()
|
|
{
|
|
reject(QStringLiteral("timeout"));
|
|
}
|
|
|
|
|
|
void Promise::resolve(const QVariant &value)
|
|
{
|
|
if (m_resultSet)
|
|
return;
|
|
m_resultSet = true;
|
|
|
|
m_timeout->stop();
|
|
m_resolveFn(value);
|
|
}
|
|
|
|
|
|
void Promise::reject(const QVariant &value)
|
|
{
|
|
if (m_resultSet)
|
|
return;
|
|
m_resultSet = true;
|
|
|
|
m_timeout->stop();
|
|
m_rejectFn(value);
|
|
}
|
|
|
|
|
|
Promise &Promise::resolved(ResultFunction resolveFn)
|
|
{
|
|
m_resolveFn = resolveFn;
|
|
return *this;
|
|
}
|
|
|
|
|
|
Promise &Promise::rejected(ResultFunction rejectFn)
|
|
{
|
|
m_rejectFn = rejectFn;
|
|
return *this;
|
|
}
|
|
|
|
}
|