Success Callback for emit method in socket.io

前端 未结 2 1385
[愿得一人]
[愿得一人] 2021-01-31 05:14

Im trying to emit a custom message from my client. I need to perform some actions on its success and failure. Now, how can i attach the success callback to emit method?

2条回答
  •  长情又很酷
    2021-01-31 05:34

    If you look at the docs, it shows you an example of passing a call back function -2nd last example: http://socket.io/docs/#Sending-and-getting-data-acknowledgements

    Ex server:

        socket.on('formData', 
                  function(data, fn){
                          // data is your form data from the client side
                          // we are here so we got it successfully so call client callback
                          // incidentally(not needed in this case) send back data value true 
                          fn(true);
                  }
                 );
    

    client:

          socket.emit('formData', 
                      data, 
                      function(confirmation){
                              // send data
                              // know we got it once the server calls this callback      
                              // note -in this ex we dont need to send back any data 
                              // - could just have called fn() at server side
                              console.log(confirmation);
                      }
                     );
    

提交回复
热议问题