如何确保回调函数已调用(触发)?
我正在使用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
});
我想在服务器代码中知道,以检测函数是否在客户端调用。
答案 0 :(得分:1)
您可以转换函数以使其异步(请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
它看起来像这样:
socket.on('message', async function(data, callback) {
const result = await callback(); // confirm we received the message
console.log(result); //returns whatever the callback function returned
});
答案 1 :(得分:1)
如果我对您的了解很好,要在您的服务器中检测是否已在客户端中调用了回调,您可以在服务器中使用计时器并发出客户确认。
让我进一步解释一下。
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秒钟后,我们显示了叉号(☓),您也可以在两个菜单中都使用所需的任何功能案件。我们涵盖了两个方向。
希望获得帮助,或者至少将您指向正确的方向:)