Really struggling with callbacks in node.js. I have:
server.js(abriged):
const classjs = require('./Class.js');
let clients = new classjs.clients();
let test = clients.getid(ws);
console.log(test);
This is returning undefined. I have
Class.js:
class clients{
constructor(){
this.WebSocket = [];
}
add(ws){
this.WebSocket.push(ws);
return this.WebSocket.length-1;
}
getid(ws){
let i=0;
this.WebSocket.forEach(element => {
if(ws == element){
console.log("true");
console.log(i);
return i;
}
i ;
});
}
}
I can see the index hitting the return but it's coming out as undefined from what I believe is the asynchronous nature of node.js.
Would a promise or callback be better here? How would I implement that?
CodePudding user response:
There is nothing asynchronous in this code. The problem is that .forEach()
does not support early return from the parent function. When you do return i
, you're returning from the .forEach()
callback, not from the getid()
function. All the return i
does there is finish the current iteration. It doesn't stop the rest of the iterations and it doesn't return at all from the parent function.
This is yet another reason why .forEach()
is essentially obsolete. I never use it any more because it has far less control flow options than a plain for
loop. Switch your code to a plain for
loop and then the return i
will work just fine.
getid(ws){
for (let [i, element] of this.WebSocket.entries()) {
if (ws === element) {
return i;
}
}
}
Or, you can just use .indexOf()
and let it search the array for you:
getid(ws){
return this.WebSocket.indexOf(ws);
}
This will return -1
if not found.