-3
socket.on('res', function(data) {  
    peanuts = data;
});


abc = function(){
    peanuts = [];
    socket.emit('req', index);
    while (!peanuts[0]) {};    
    return peanuts[0];
};

like this, infinite loop.

abc = function(){
peanuts = [];
var intr = setInterval(function(){
    if (peanuts[0]) {
        clearInterval(intr);            
    };
}, 100)
return peanuts[0];

};

like this, it returns "peanuts[0]" before the "peanuts = data;"

pls help me.


socket.emit('req', index, function(answer) {
    console.log(answer);
});  
console.log('duck');

found that it could sending with acknowledgement.. but i want console.log(answer) run before console.log('duck')


OK,Actually my code is like this..

function poo() {
    var x = a() & b();
    /*
    blablabla.....
    */
    return z;
}

function a() {
    socket.emit('req', index, function(answer) {
        var temp = answer
    });  
    return temp;
}

console.log(poo());

And if I use that ‘sync style’(but not sync), I need to rewrite function poo,right? That's why I want sync, for some reason, I can only rewrite function a, so, is it possible to check as the condition of while instead of emit with acknowledgement or using listener?

Like this?

function a() {
    socket.emit('req', index);
    while (!socket.???) {
    };
    return socket.????;
}
something
  • 1
  • 1
  • Don't think it's possible. – ASDFGerte Jun 04 '18 at 17:51
  • Freezing while waiting for an asynchronous operation to finish is the exact opposite of what you want to do. It also looks like you're trying to use sockets like an ajax request. That's a bit of an anti-pattern too. Use an ajax request if you expect an immediate response on the request – baao Jun 04 '18 at 17:53
  • @baao Ajax wont give you an immediate response either, unless usimg webworker and even then not ideal. – Keith Jun 04 '18 at 18:02
  • Of course not an immediate response. But if you look at his code, that's an ajax request, not something you handle with sockets. @Keith – baao Jun 04 '18 at 18:33
  • pls look the new code,hope it makes my question more clear, i want console.log(answer) run before console.log('duck'), is it possible if i use ajax request? @baao – something Jun 04 '18 at 18:49
  • If you're working with promises, yes. Otherwise no – baao Jun 04 '18 at 18:50
  • Really - and that's meant only friendly - as long as you don't understand async behavior and principles, working with websockets is above your head. Here's a good starter https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – baao Jun 04 '18 at 18:52
  • @baao I'm not sure what you mean by it's an AJax request,. What he's doing can be Ajax or Sockets, it doesn't really matter. I'm using socket.io for all my IPC needs now, were in the past I might have used long poling Ajax requests. I still use Ajax (or better still fetch) for resources were caching make sense. But back to the problem of the OP, what he really needs to do is embrace`async`, because in Javascript `sync` is just a No/No.. – Keith Jun 04 '18 at 19:25
  • Don't take the naming ajax so serious, it's just easier to write and people know what is meant. Of course you would use fetch... The question is not talking about long polling. He's sending an request from the frontend and is expecting a response on this request from the backend. You'd use a webrequest (fetch) for that. I already posted a link for the OP to learn about async behavior in code - as you say sync or blocking like he asked for is a big no no. @Keith – baao Jun 04 '18 at 19:31
  • ...Instead of long polling of course sockets @Keith – baao Jun 04 '18 at 19:32
  • I really want sync, is it impossible in this case? – something Jun 05 '18 at 07:24

1 Answers1

0

Is it possible to freeze while waiting for a socket?

No, it is not possible in Javascript. You can't "block" the interpreter while waiting for a network event to arrive. Because of the event-driven design of Javascript, if you do a while() loop that tries to wait for the value, the while() loop will block the event loop so that the result can never get processed. Thus, you end up with a deadlock and essentially a loop that never completes.

I really want sync, is it impossible in this case?

It is impossible. The event-driven nature of Javascript and socket.io requires you to use that event-driven architecture, not a blocking, synchronous architecture. To use a blocking, synchronous architecture, you will need a different language and environment that supports threads and blocking I/O (like Java, for example).

The operation is asynchronous so you have to program your function to properly return value asynchronously. The function should either return a promise that resolves when the value arrives or the function should take a callback that you will call when the value arrives. Or, you can just use the callback already built into .emit() directly to process the result in the callback (as shown below).

The calling code then needs to adapt to use the asynchronous result. That's how async programming works in Javascript. To use asynchronous operations, you have to learn how to program asynchronously.

You need to write event-driven code, not blocking code. Set up event listeners or promises and then continue your process when that event fires or the callback is called. It's hard to make a concrete suggestion for how your code should work because you are showing mostly pseudo-code, not real code.

For more detail on returning an async value, you can see this canonical answer on the topic.


FYI, if you're trying to use socket.io in a mode that's kind of like request/response where you want a specific response from a request message sent, then socket.io has a feature for that using a callback on the .emit() (the server has to cooperate to make this work):

socket.emit('req', index, function(answer) {
    // put code here that uses the answer
});  

This is how you do async response handling in Javascript. You don't write sequential, synchronous functions. You use an event driven callback.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @something - Does this answer your question? If so, please indicate that to the community by clicking the checkmark to the left of the answer. That will also earn you some reputation points for following the proper procedure here. If not, then please indicate what is not yet answered. – jfriend00 Jun 26 '18 at 05:26