Skip to content

Commit 4ed2fe7

Browse files
committed
improve unhandled rejections
1 parent 65ae47f commit 4ed2fe7

File tree

1 file changed

+41
-24
lines changed

1 file changed

+41
-24
lines changed

src/worker.js

Lines changed: 41 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,23 @@ addEventListener('message', ({ data }) => {
2727
if (data.type === 'evaluate') {
2828
const { state, code } = data.value;
2929

30+
const promises = new Set();
3031
try {
3132
initializeAgent({
3233
features: [...state.get('features')],
3334
promiseRejectionTracker(promise, operation) {
35+
switch (operation) {
36+
case 'reject':
37+
promises.add(promise);
38+
break;
39+
case 'handle':
40+
promises.delete(promise);
41+
break;
42+
default:
43+
break;
44+
}
3445
if (operation === 'reject') {
35-
postMessage({
36-
type: 'unhandledRejection',
37-
// eslint-disable-next-line no-use-before-define
38-
value: inspect(promise.PromiseResult, realm),
39-
});
46+
promises.add(promise);
4047
}
4148
},
4249
});
@@ -57,28 +64,30 @@ addEventListener('message', ({ data }) => {
5764
}, [], realm);
5865
Abstract.CreateDataProperty(realm.global, new Value(realm, 'print'), print);
5966

60-
const console = new APIObject(realm);
61-
Abstract.CreateDataProperty(realm.global, new Value(realm, 'console'), console);
67+
{
68+
const console = new APIObject(realm);
69+
Abstract.CreateDataProperty(realm.global, new Value(realm, 'console'), console);
6270

63-
[
64-
'log',
65-
'warn',
66-
'debug',
67-
'error',
68-
'clear',
69-
].forEach((method) => {
70-
const fn = new Value(realm, (args) => {
71-
postMessage({
72-
type: 'console',
73-
value: {
74-
method,
75-
values: args.map((a) => inspect(a)),
76-
},
71+
[
72+
'log',
73+
'warn',
74+
'debug',
75+
'error',
76+
'clear',
77+
].forEach((method) => {
78+
const fn = new Value(realm, (args) => {
79+
postMessage({
80+
type: 'console',
81+
value: {
82+
method,
83+
values: args.map((a) => inspect(a)),
84+
},
85+
});
86+
return Value.undefined;
7787
});
78-
return Value.undefined;
88+
Abstract.CreateDataProperty(console, new Value(realm, method), fn);
7989
});
80-
Abstract.CreateDataProperty(console, new Value(realm, method), fn);
81-
});
90+
}
8291

8392
postMessage({
8493
type: 'console',
@@ -114,5 +123,13 @@ addEventListener('message', ({ data }) => {
114123
},
115124
});
116125
}
126+
127+
for (const promise of promises) {
128+
postMessage({
129+
type: 'unhandledRejection',
130+
// eslint-disable-next-line no-use-before-define
131+
value: inspect(promise.PromiseResult, realm),
132+
});
133+
}
117134
}
118135
});

0 commit comments

Comments
 (0)