如何确定回调函数已调用(触发)?
我正在使用 socket.io 和回调函数,请查看我的代码:
// server
socket.emit('message', message, function() {
// some code
});
// client
socket.on('message', function(data, callback) {
callback(); // confirm we received the message
// some code
});
我想知道在服务器代码中,检测函数是否在客户端调用。
最佳答案
如果我理解得很好,要在您的服务器中检测您的回调是否已在客户端中调用,您可以在服务器中使用计时器并发出客户端确认。
让我进一步解释一下。
1) 服务器
// 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)客户
// Listen message from the Server
socket.on('message', msg => {
// Send confirmation (your callback)
socket.emit('confirmation', id)
})
3) 服务器
// Listen confirmation from the Client
socket.on('confirmation', id => {
// Avoid timer
clearTimeout(timer)
// Send back confirmation
io.emit('confirmation', id)
})
这是一个完整的工作示例:
服务器 (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'))
客户端 (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>
如果您没有收到复选符号 (✓),则表示消息有问题,5 秒后我们在服务器中显示十字符号 (☓),您也可以在两者中使用任何您想要的功能个案。我们涵盖两个方向。
希望这对您有所帮助,或者至少能为您指明正确的方向:)
关于javascript - 如何确定回调函数是否已调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56869490/