-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsAsync.h
More file actions
30 lines (24 loc) · 803 Bytes
/
JsAsync.h
File metadata and controls
30 lines (24 loc) · 803 Bytes
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
#pragma once
#include <QJSEngine>
#include <QtConcurrent>
class JsAsync : public QObject
{
public:
explicit JsAsync(QObject *_parent = nullptr)
: QObject(_parent)
{ }
template <typename T>
void makeAsync(const QJSValue &callback, std::function<T()> func){
auto *watcher = new QFutureWatcher<T>(this);
QObject::connect(watcher, &QFutureWatcher<T>::finished, this, [this, watcher, callback]() {
T returnValue = watcher->result();
QJSValue cbCopy(callback);
QJSEngine *engine = qjsEngine(this);
cbCopy.call(QJSValueList { engine->toScriptValue(returnValue) });
watcher->deleteLater();
});
watcher->setFuture(QtConcurrent::run( [=]() {
return func();
}));
}
};