hi everyone I'm facing difficulty while using a local variable of a function outside of it, is there any way to do that.
instance.onmessage = (e) => {
let color = e.data
return color;
};
I'm getting color from instance.onmessage and I have to use this color in the code below.
visualLinks.lineStyle(
2,
link.edgeType === value ? 0xff0000 : color
);
instance.onmessage = (e) => {
let color=e.data
return color;
};
visualLinks.lineStyle(
2,
link.edgeType === value ? 0xff0000 : color
);
I know that this is wrong but I have to perform something like this for reference only, I wrote this code.
You can't use a local variable of a function outside of that function in JavaScript. You could make it a global variable instead:
let color = undefined;
window.onmessage = (e) => {
color = e.data
};
// THIS WILL NOT WORK (because color is still undefined)
console.log(color);
visualLinks.lineStyle(
2,
link.edgeType === value ? 0xff0000 : color
);
In the case of your code which uses onmessage(), your onmessage callback function won't have been run (your function doesn't run until a message is received) in time for any code right after it.
You could wait to run that code until the message is received by moving it inside of the function.
let color = undefined;
window.onmessage = (e) => {
color = e.data;
console.log(color);
visualLinks.lineStyle(
2,
link.edgeType === value ? 0xff0000 : color
);
};
If this is too simple an answer to be useful, you may have better luck if you include a more realistic example of what you're trying to do.