0
function get_socketId(host,port) {
      var socketId = -1;

      chrome.sockets.tcp.create({}, function(createInfo) {
            chrome.sockets.tcp.connect(createInfo.socketId, host, port, function(result) {
                if(result >= 0){
                     socketId = createInfo.socketId;
                     console.log(socketId);
                     return socketId;
                }
            });
     });
     return socketId;
}

when this function is called:

console.log(get_socketId("irc.freenode.com", 6667));

always returns -1, while showing for e.x 3 in the console. what am i doing wrong?

  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Xan Feb 29 '16 at 15:33

2 Answers2

1
chrome.sockets.tcp.create({}, function(createInfo) {});

is an async function the outter sockeId return will hapen earlier then the inner. So the return is -1 cuz the inner functions are not even called when the socketId at the bottom returns.

One possible solution is to create an async function and pass the socketId variable to the callback:

function get_socketId(host,port, callback) {
  var socketId = -1;

  chrome.sockets.tcp.create({}, function(createInfo) {
        chrome.sockets.tcp.connect(createInfo.socketId, host, port,   function(result) {
            if(result >= 0){
                 socketId = createInfo.socketId;
                 console.log(socketId);
                 callback(null, socketId); //we pass no error and the socketId to our callback function
            } else {
                 callback('no result', null); //we pass an error
            }
        });
 });
};
//call the function here
  get_socketId("irc.freenode.com", 6667, function (err, socketId){
    if (err){
       console.error(err);
    } else { //if no error were passed 
       console.log(socketId);
    }    
 });
kailniris
  • 8,856
  • 2
  • 17
  • 24
  • new problem now... i'm using it with angularJS, if i set some stuff at "console.log(socketId);" when there is no error the html isn't changing. – YonatanHanan Feb 29 '16 at 16:33
  • Its hard to tell what can be the problem without looking at the code. You should create another question with the new code in it. – kailniris Feb 29 '16 at 16:46
-1

Make your variable in global scope, that will stop all your problems.

var socketId;

function get_socketId(host,port) {
      socketId = -1;
      chrome.sockets.tcp.create({}, function(createInfo) {
            chrome.sockets.tcp.connect(createInfo.socketId, host, port, function(result) {
                if(result >= 0){
                     socketId = createInfo.socketId;
                     console.log(socketId);
                }
            });
     });
     return socketId;
}
Jason Lipo
  • 751
  • 2
  • 11
  • 24