72 lines
1.7 KiB
JavaScript
72 lines
1.7 KiB
JavaScript
export default class SandboxMessenger {
|
|
constructor() {
|
|
this.messageQueue = [];
|
|
this.responseQueue = [];
|
|
this.isProcessing = false;
|
|
}
|
|
|
|
async sendMessage(message) {
|
|
return new Promise((resolve, reject) => {
|
|
this.messageQueue.push({ message, resolve, reject });
|
|
this.processMessages();
|
|
});
|
|
}
|
|
|
|
async receiveMessage() {
|
|
return new Promise((resolve) => {
|
|
this.responseQueue.push(resolve);
|
|
this.processMessages();
|
|
});
|
|
}
|
|
|
|
async processMessages() {
|
|
if (this.isProcessing) {
|
|
return;
|
|
}
|
|
|
|
this.isProcessing = true;
|
|
|
|
while (this.messageQueue.length > 0 && this.responseQueue.length > 0) {
|
|
const { message, resolve, reject } = this.messageQueue.shift();
|
|
const responseCallback = this.responseQueue.shift();
|
|
|
|
try {
|
|
// Send the message to the Main Thread and wait for the response
|
|
const response = await this.sendMessageToMainThread(message);
|
|
|
|
// Resolve the promise with the response
|
|
resolve(response);
|
|
|
|
// Call the response callback with the response
|
|
responseCallback(response);
|
|
} catch (error) {
|
|
// Reject the promise with the error
|
|
reject(error);
|
|
}
|
|
}
|
|
|
|
this.isProcessing = false;
|
|
}
|
|
|
|
async sendMessageToMainThread(message) {
|
|
return new Promise((resolve, reject) => {
|
|
// Send the message to the Main Thread
|
|
postMessage(message);
|
|
|
|
// Listen for the response from the Main Thread
|
|
const messageHandler = (event) => {
|
|
const response = event.data;
|
|
|
|
// Remove the event listener
|
|
removeEventListener('message', messageHandler);
|
|
|
|
// Resolve the promise with the response
|
|
resolve(response);
|
|
};
|
|
|
|
// Add the event listener for the response
|
|
addEventListener('message', messageHandler, { once: true });
|
|
});
|
|
}
|
|
}
|