jmesnil / stomp-websocket

Stomp client for Web browsers and node.js apps
http://jmesnil.net/stomp-websocket/doc/
Apache License 2.0
1.43k stars 587 forks source link

subscribe inside forloop would not trigger call back #156

Open xingguo3 opened 4 years ago

xingguo3 commented 4 years ago

STOMP over ws connection and send to topic are normal.

//1. in js, the subscribe could only trigger the latest callback // console output only print "callback 3" for(var i= 0;i<4;i++){ client.subscribe("/topic/topicid_"+i, function(message){ console.log("callback " + i); }); }

// 2. if subscribe one by one, could get all console output client.subscribe("/topic/topicid"+0, function(message){ console.log("callback " + 0); }); client.subscribe("/topic/topicid"+1, function(message){ console.log("callback " + 1); }); client.subscribe("/topic/topicid"+2, function(message){ console.log("callback " + 2); }); client.subscribe("/topic/topicid"+3, function(message){ console.log("callback " + 3); });

any idea or solution to solve this issue?

ryanvs commented 4 years ago

The issue is the use of a JavaScript closure inside the for loop. You defined the local variable i in the loop, so it will use the last value only. Please see https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example for more information.