-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjspromise.h
45 lines (35 loc) · 1.22 KB
/
jspromise.h
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
#ifndef JSPROMISE_H
#define JSPROMISE_H
#include <QJSEngine>
/***
* A Promise object to be used with QML
*
*/
class JSPromise : public QObject {
Q_OBJECT
public:
explicit JSPromise(QJSEngine *parent) : QObject(parent), engine(parent) {
connect(this, &JSPromise::resolveJSValue, this, &QObject::deleteLater);
connect(this, &JSPromise::reject, this, &QObject::deleteLater);
}
QJSValue toJSValue() { return engine->toScriptValue(this); }
Q_INVOKABLE QJSValue then(QJSValue func) {
connect(this, &JSPromise::resolveJSValue, this, [func](auto value) { func.call({value}); });
return toJSValue();
}
Q_INVOKABLE QJSValue onFailed(QJSValue func) {
connect(this, &JSPromise::reject, this, [func](auto msg) { func.call({msg}); });
return toJSValue();
}
Q_INVOKABLE QJSValue finally(QJSValue func) {
connect(this, &JSPromise::destroyed, this, [func]() { func.call(); });
return toJSValue();
}
template <class T> void resolve(T value) { emit resolveJSValue(engine->toScriptValue(value)); }
signals:
void resolveJSValue(QJSValue value);
void reject(const QString &message);
private:
QJSEngine *engine;
};
#endif // JSPROMISE_H