Skip to content

Commit e43342b

Browse files
committed
SimpleChatTC:ChatMessageEx: 1st go at trying to track promises
1 parent 8a28b33 commit e43342b

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

tools/server/public_simplechat/toolsworker.mjs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,19 @@
55
//
66

77
/**
8-
* Expects to get a message with identifier name and code to run
9-
* Posts message with identifier name and data captured from console.log outputs
8+
* Expects to get a message with id, name and code to run
9+
* Posts message with id, name and data captured from console.log outputs
1010
*/
1111

1212

1313
import * as tconsole from "./toolsconsole.mjs"
14+
import * as xpromise from "./xpromise.mjs"
1415

1516

16-
self.onmessage = function (ev) {
17+
self.onmessage = async function (ev) {
1718
tconsole.console_redir()
1819
try {
19-
eval(ev.data.code)
20+
await xpromise.evalWithPromiseTracking(ev.data.code);
2021
} catch (/** @type {any} */error) {
2122
console.log(`\n\nTool/Function call "${ev.data.name}" raised an exception:${error.name}:${error.message}\n\n`)
2223
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
//@ts-check
2+
// Helpers for a tracked promise land
3+
// by Humans for All
4+
//
5+
6+
7+
/**
8+
* @typedef {(resolve: (value: any) => void, reject: (reason?: any) => void) => void} PromiseExecutor
9+
*/
10+
11+
12+
/**
13+
* Eval which allows promises generated by the evald code to be tracked.
14+
* @param {string} codeToEval
15+
*/
16+
export function evalWithPromiseTracking(codeToEval) {
17+
const _Promise = globalThis.Promise;
18+
/** @type {any[]} */
19+
const trackedPromises = [];
20+
21+
const Promise = function ( /** @type {PromiseExecutor} */ executor) {
22+
const promise = new _Promise(executor);
23+
trackedPromises.push(promise);
24+
25+
promise.then = function (...args) {
26+
const newPromise = _Promise.prototype.then.apply(this, args);
27+
trackedPromises.push(newPromise);
28+
return newPromise;
29+
};
30+
31+
promise.catch = function (...args) {
32+
const newPromise = _Promise.prototype.catch.apply(this, args);
33+
trackedPromises.push(newPromise);
34+
return newPromise;
35+
};
36+
37+
return promise;
38+
};
39+
40+
Promise.prototype = _Promise.prototype;
41+
Object.assign(Promise, _Promise);
42+
43+
eval(codeToEval);
44+
45+
return _Promise.all(trackedPromises);
46+
}

0 commit comments

Comments
 (0)