-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPromise.cpp
48 lines (38 loc) · 1.73 KB
/
Promise.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "Promise.hpp"
#include <QQmlComponent>
#include <QQmlEngine>
QmlPromise::QmlPromise(QObject* parent)
: QObject(parent) {
QQmlComponent promiserComponent(qmlEngine(parent));
promiserComponent.setData("import QuickPromise 1.0\nPromise {}", QUrl());
internalPromise = promiserComponent.create();
QQmlEngine::setObjectOwnership(internalPromise, QQmlEngine::JavaScriptOwnership);
connect(internalPromise, &QObject::destroyed, this, [this] { internalPromise = nullptr; });
connect(internalPromise, SIGNAL(fulfilled(QVariant)), this, SIGNAL(fulfilled(QVariant)));
connect(internalPromise, SIGNAL(rejected(QVariant)), this, SIGNAL(rejected(QVariant)));
connect(internalPromise, SIGNAL(settled(QVariant)), this, SIGNAL(settled()));
connect(this, &QmlPromise::fulfilled, [this] { wasFulfilled = true; });
connect(this, &QmlPromise::rejected, [this] { wasRejected = true; });
}
QmlPromise::~QmlPromise() {
}
bool QmlPromise::isFulfilled() {
return internalPromise? internalPromise->property("isFulfilled").toBool() : wasFulfilled;
}
bool QmlPromise::isRejected() {
return internalPromise? internalPromise->property("isRejected").toBool() : wasRejected;
}
bool QmlPromise::isSettled() {
return internalPromise? internalPromise->property("isSettled").toBool() : wasFulfilled || wasRejected;
}
QmlPromise::operator QJSValue() {
return qmlEngine(internalPromise)->toScriptValue(internalPromise);
}
void QmlPromise::resolve(QVariant args) {
if (internalPromise)
QMetaObject::invokeMethod(internalPromise, "resolve", Q_ARG(QVariant, args));
}
void QmlPromise::reject(QVariant reason) {
if (internalPromise)
QMetaObject::invokeMethod(internalPromise, "reject", Q_ARG(QVariant, reason));
}