javascript - 异步函数挂起/恢复时是否可以透明地触发回调?
问题描述
我确实意识到我可以包装单个等待,但我正在寻找更多透明/中间件解决方案,可以包装异步函数并在每个等待内部触发前/后回调。
所需功能的伪代码示例:
const suspendCallback () => console.log('Releasing the event loop');
const resumeCallback () => console.log('Reclaiming the event loop');
let work1 = () => new Promise(() => setTimeout(() => null, 1000))
let work2 = () => new Promise(() => setTimeout(() => null, 1000))
let work3 = () => new Promise(() => setTimeout(() => null, 1000))
// somehow bind the callbacks to this function:
const doTheThing = async () => {
await work1();
await work2();
await work3();
};
doTheThing();
// Would print 'Releasing the event loop' each time doTheThing
// suspends, and 'Reclaiming the event loop' each time execution
// is resumed (the promise resolves). Thus:
> 'Releasing the event loop'
'Reclaiming the event loop'
'Releasing the event loop'
'Reclaiming the event loop'
'Releasing the event loop'
'Reclaiming the event loop'
解决方案
您可能正在寻找node.js 中的异步钩子,它可以跟踪 promises。
语言中没有标准的内置结构。如果您想基于这样的东西构建自己的框架,请改用生成器函数并提供一个运行器来逐步执行生成的任务。
推荐阅读
- swift - jonkykong/侧边菜单。无法让选项工作
- javascript - push 不是函数 vuejs
- uuid - MacOS 上的 uuidgen 生成所有大写字母
- http - 为什么 HTTP 版本号同时出现在请求行和状态行中?
- python - 如何使 python 程序可以从命令行普遍执行?
- gremlin - 图表未保存
- c++ - 使用 SFINAE 和 void_t 确定容器内元素的类型
- pypi - 如何更新 pip 包而不将其 CSV 文件重置为其原始状态
- typescript - 带有节点服务器的 tsconfig“模块”属性 + 创建 React 应用程序
- ionic-framework - 有没有办法让 ion-segment 在 iOS 和 Android 上看起来一样?