-
Notifications
You must be signed in to change notification settings - Fork 0
/
async-worker.js
42 lines (39 loc) · 1.14 KB
/
async-worker.js
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
/**
* @param {Worker} worker
* @param {any} message
* @returns {Promise<any>}
*/
function sendMessageToWorker(worker, message) {
return new Promise((resolve, _reject) => {
const messageId = Date.now() + Math.random(); // Generate a unique ID
/**
* @param {MessageEvent<any>} event
*/
const handleMessage = (event) => {
if (event.data.messageId === messageId) {
// Check if the response matches
worker.removeEventListener("message", handleMessage); // Cleanup
resolve(event.data); // Resolve the promise with the response
}
};
worker.addEventListener("message", handleMessage);
worker.postMessage({ messageId, ...message }); // Send the message with the ID
});
}
/**
* @param {string} query
*/
async function sql(query) {
/**
* @type {{success: true, resultRows: any[], columnNames: string[]} | {success: false, error: string}}
*/
const result = await sendMessageToWorker(window.sqlite3Worker, {
type: "syncExec",
sql: query,
});
if (!result.success) {
alert(`${result.error} in query ${query}`);
throw new Error(result.error);
}
return result;
}