【发布时间】:2021-02-01 23:36:07
【问题描述】:
我正在构建一个 socket.io Node JS 应用程序,我的 socket.io 服务器将监听来自许多 socket.io 客户端的数据,我需要尽快通过我的 socket.io 服务器将数据保存到 API并认为 async/await 是最好的前进方式。
现在,我的 .on('connection') 中有一个函数,但有没有办法可以将其设为异步函数,而不是在其中包含嵌套函数?
io.use((socket, next) => {
if (!socket.handshake.query || !socket.handshake.query.token) {
console.log('Authentication Error 1')
return
}
jwt.verify(socket.handshake.query.token, process.env.AGENT_SIGNING_SECRET, (err, decoded) => {
if (err) {
console.log('Authentication Error 2')
return
}
socket.decoded = decoded
next()
})
}).on('connection', socket => {
socket.on('agent-performance', data => {
async function savePerformance () {
const saved = await db.saveToDb('http://127.0.0.1:8000/api/profiler/save', data)
console.log(saved)
}
savePerformance()
})
})
【问题讨论】: