javascript - 从外部异步函数发送快速响应
问题描述
setTimeout
在 express 路由之外有一个函数(类似于,异步工作)。在我的例子中,它是一个监听来自 SocketIO 的事件的函数。是否可以从它发送响应?
setTimeout(() => {
res.send('Got it');
}, 1000)
app.get('/endpoint', (req, res) => {
// wait for event 'res' from setTimout
});
解决方案
如果您只想从另一个函数发送响应,您可以将其传递res
给它以发送响应。
如果您需要在路由中做更多工作,但只有在其他函数发送响应之后(为什么?),那么您可以将其更改为返回一个 Promise:
const someFunction = res =>
new Promise((resolve) => {
setTimeout(() => {
res.send('Got it');
resolve();
}, 1000);
});
app.get('/endpoint', async (req, res) => {
await someFunction(res);
console.log('this will only be called after res sent');
});
推荐阅读
- html - 背景未显示,使用外部 css
- html - SCSS:自动生成的供应商前缀杀死输入占位符样式
- python - 如何根据另一列的行值查看另一列的数据?
- python - EJBCA SOAP 接口返回索引超出范围异常
- django - 一次更新一对相关对象的原子事务
- reactjs - 无法使用 flex-box 和 styled-components 水平排列项目列表
- machine-learning - 根据新数据微调 GPT-2/3
- javascript - 有没有办法找到在哪个文件中定义了函数或属性?
- python - 检查 dtype:object 是否为 NaN
- kubernetes - Kubernetes 上的 Gitlab 管道部署问题