Skip to content

Commit 3a03cce

Browse files
committed
Fix scala-js/scala-js#3411: Do not call onMessage immediately after init
This change contains a fix to this in the Node.js Com support and a test in the test suite for this.
1 parent 40e8167 commit 3a03cce

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

js-envs-test-kit/src/main/scala/org/scalajs/jsenv/test/TimeoutComTests.scala

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,21 @@ private[test] class TimeoutComTests(config: JSEnvSuiteConfig) {
8686
""", RunConfig())
8787
run.closeAndWait()
8888
}
89+
90+
@Test // #3411
91+
def noImmediateCallbackTest: Unit = {
92+
val run = kit.start(s"""
93+
setTimeout(function() {
94+
var gotCalled = false;
95+
scalajsCom.init(function(msg) { gotCalled = true; });
96+
if (gotCalled) throw "Buffered messages did not get deferred to the event loop";
97+
}, 100);
98+
""", RunConfig())
99+
100+
try {
101+
run.run.send("Hello World")
102+
} finally {
103+
run.closeAndWait()
104+
}
105+
}
89106
}

nodejs-env/src/main/scala/org/scalajs/jsenv/nodejs/ComSupport.scala

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ object ComRun {
251251
| var inMessages = [];
252252
|
253253
| // The callback where received messages go
254-
| var recvCallback = function(msg) { inMessages.push(msg); };
254+
| var onMessage = null;
255255
|
256256
| socket.on('data', function(data) {
257257
| inBuffer = Buffer.concat([inBuffer, data]);
@@ -268,7 +268,8 @@ object ComRun {
268268
|
269269
| inBuffer = inBuffer.slice(byteLen);
270270
|
271-
| recvCallback(res);
271+
| if (inMessages !== null) inMessages.push(res);
272+
| else onMessage(res);
272273
| }
273274
| });
274275
|
@@ -280,12 +281,14 @@ object ComRun {
280281
| socket.on('close', function() { process.exit(0); });
281282
|
282283
| global.scalajsCom = {
283-
| init: function(recvCB) {
284-
| if (inMessages === null) throw new Error("Com already initialized");
285-
| for (var i = 0; i < inMessages.length; ++i)
286-
| recvCB(inMessages[i]);
287-
| inMessages = null;
288-
| recvCallback = recvCB;
284+
| init: function(onMsg) {
285+
| if (onMessage !== null) throw new Error("Com already initialized");
286+
| onMessage = onMsg;
287+
| process.nextTick(function() {
288+
| for (var i = 0; i < inMessages.length; ++i)
289+
| onMessage(inMessages[i]);
290+
| inMessages = null;
291+
| });
289292
| },
290293
| send: function(msg) {
291294
| var len = msg.length;

0 commit comments

Comments
 (0)