Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

subscribe inside forloop would not trigger call back #156

Open
xingguo3 opened this issue Mar 11, 2020 · 1 comment
Open

subscribe inside forloop would not trigger call back #156

xingguo3 opened this issue Mar 11, 2020 · 1 comment

Comments

@xingguo3
Copy link

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
Copy link

ryanvs commented Jun 23, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants