I'm new to javascript and was trying to figure out why the following code was not working:
let ws = new WebSocket("ws://echo.websocket.org/");
ws.onmessage = msg => console.log(msg);
let queue = [];
ws.onopen = () => {
queue.forEach(msg => ws.send(msg));
};
const send = () => {
if(ws.readyState === ws.OPEN){
ws.send(msg);
}
else{
queue.push(msg);
}
};
send("foo");
send("bar");
Then I realized that I needed: let send = (msg) => {
.
Before finding the problem, I had used lint and dev tools but I cdidn't see any warnings. What should I be doing to find there kinds of problems?
eslint. There's even a specific rule for this one: http://eslint.org/docs/rules/no-undef
You should probably get a ReferenceError, because your let/const implies strict syntax, though if you missed that I'm guessing your engine wasn't picking up on strict mode for whatever reason. It's a better error to find with static analysis anyway, because it will pick up the error even if the function is never called.
I recommend you give TypeScript a try. Have a look at your example at TypeScript playground .
It will immediatelly tell you: Cannot find name msg
inside your send
function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.