Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
Websocket response data undefined in global variable

I would like to use the global variable data and assign the WebSocket response data to it but inside the function the data is displayed outside is undefined.

How can I solve this?

var data;

client.onopen = () => {
  console.log("WebSocket Client Connected!");
};

client.onmessage = (message) => {
  data = message.data;
  console.log(data); // json data in console
};

client.onerror = function () {
  console.log("Connection Error");
};

console.log(data); // undefined
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It is because the last console.log happens before the socket event happens that why the variable is undefined if you want to see the variable you need to call it by function after the socket event emited

about 4 years ago · Juan Pablo Isaza Report

0

The data variable is not defined at the time when console.log executes, you tried to log the variable to the console before your client received the message.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!