0

I would like to know how to wait on an socket.on call. I know that one could use the callbacks as described here, but this is not applicable in my case (at least I think it is not). The following is what I have:

index.html

...
socket.on('update_img', function(data) {
    // Do something
});

scanner.addListener('scan', function(content) {
    socket.emit('answer', content);
});

and then on the server:

...
client.emit('update_img', some_data);
...
client.on('answer', function(data) {
    // do something with the answer
});

what basically happens, I send something to the frontend which then generates an image. At the same time, the library in the browser (instascan, thus scanner.addListener) waits for reading a QR-code and sends its content back to the server. So what I now need is that client.on('answer', ...); waits for this answer.

Is there any way to achieve this?

Dr3w Br1ck13
  • 187
  • 1
  • 5
  • 14

1 Answers1

0

Essentially with client.on(...) you're adding the callback to that event, meaning that whenever that "anwser" event ist emitted from the client, it will be called on the server.

So if you make sure that socket.emit("anwser") on the client, is only called after you sent the image from the server, the server just has to listen to the "anwser" event and may assume that everything happened as expected.

Therefore you dont actually have to "wait" explicitly.

EDIT: Misunderstood your flow. Will update my answer

ThatBrianDude
  • 2,952
  • 3
  • 16
  • 42
  • I need to wait for the content in order to complete the request correctly. – Dr3w Br1ck13 Nov 13 '17 at 12:43
  • The content is provided through the "update_img" event right? – ThatBrianDude Nov 13 '17 at 12:45
  • update_image simply updates an image on the screen. the scanner scans a qr-code where it's content needs to be handled and sent back as a request answer – Dr3w Br1ck13 Nov 13 '17 at 12:49
  • Im not sure where the problem is then... You say that you need client.on("anwser") to wait for the anwser. It does that automatically by attaching the callback... – ThatBrianDude Nov 13 '17 at 12:52
  • when I put a log output right after client.on('answer', ...) and I don't send an socket.emit('answer', ...), the log still appears, but it should not. – Dr3w Br1ck13 Nov 13 '17 at 13:11
  • Is the console.log statement inside the callback? If you place it after client.on then of course it will be called immediately. Basicly, in the beginning your process will run from top to bottom, initializing stuff and attaching callbacks to events. From then on, node wont to anything else but fireoff callbacks and execute them. This is basic NodeJS style of working with async stuff. – ThatBrianDude Nov 13 '17 at 17:38