Warm tip: This article is reproduced from stackoverflow.com, please click
javascript socket.io

How to be sure if a callback function has called

发布于 2020-03-27 10:22:51

How to make sure a callback function has called(fired)?

I am using socket.io and callback function please check out my code:

// server
socket.emit('message', message, function() {
    // some code
});


// client
socket.on('message', function(data, callback) {
  callback(); // confirm we received the message
  // some code
});

I want to know in the server code, to detect whether function has called in the client side or no.

Questioner
Muhammad
Viewed
23
gengns 2019-07-04 08:12

If I understood you well, to detect in your server whether your callback has been called in the client or not, you can use a timer in the server and emit a confirmation in the client.

Let's me explain it further.

1) Server

// Timer to wait for your confirmation
let timer

// Listen message from the Client
socket.on('message', msg => {
  // Wait 5 s for confirmation
  timer = setTimeout(() => noConfirmation(), 5000)
  // Send message to the Clients
  io.emit('message', msg)
})

2) Client

// Listen message from the Server
socket.on('message', msg => {
  // Send confirmation (your callback)
  socket.emit('confirmation', id)
})

3) Server

// Listen confirmation from the Client
socket.on('confirmation', id => {
  // Avoid timer
  clearTimeout(timer)
  // Send back confirmation
  io.emit('confirmation', id)
})

Here you are a full working example:

Server (index.js)

const app = require('express')()
const http = require('http').createServer(app)
const io = require('socket.io')(http)

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html')
})

// Timer to wait for your confirmation
let timer

io.on('connection', socket => {
  console.log('a user connected')

  socket.on('disconnect', () => 
    console.log('user disconnected'))

  // Listen message from the Client
  socket.on('message', msg => {
    console.log(`message: ${msg}`)
    // Wait 5 s for confirmation
    timer = setTimeout(() => console.log('☓'), 5000)
    // Send message to the Clients
    io.emit('message', msg)
  })

  socket.on('confirmation', id => {
    console.log('✓')
    // Avoid timer
    clearTimeout(timer)
    // Send back confirmation
    io.emit('confirmation', id)
  })
})

http.listen(3000, () => 
  console.log('listening on *:3000'))

Client (index.html)

  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io()

      // Submit message to the Server
      const $input = document.querySelector('input');
      document.querySelector('form').onsubmit = e => {
        e.preventDefault() // prevents page reloading
        socket.emit('message', $input.value)
        $input.value = ''
      }

      // Listen message from the Server
      const $messages = document.querySelector('#messages');
      socket.on('message', msg => {
        const id = new Date().getTime()
        $messages.insertAdjacentHTML('beforeend', `<li id="m${id}">${msg}</li>`)
        // Send confirmation
        socket.emit('confirmation', id)
      })

      // Confirmation message recived
      socket.on('confirmation', id => 
        document.querySelector(`#m${id}`).insertAdjacentText('beforeend', '✓'))
    </script>
  </body>

If you don't receive the check symbol (✓) it means there was a problem with the messages and in the server after 5 seconds we show a cross symbol (☓), also you can use any function you want in both cases. We are covering both directions.

Hope this help or at least point you to the right direction : )