当异步函数挂起/恢复时,是否可以透明地触发回调



我确实意识到我可以包装单个等待,但我正在寻找更透明的/中间件解决方案,它可以包装异步函数并在内部的每个等待上触发前/后回调。

所需功能的伪代码示例:

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中寻找异步挂钩,它可以跟踪promise。

该语言中没有标准的内置构造。如果你想基于这样的东西构建你自己的框架,那么就选择生成器函数,并提供一个运行器来逐步完成生成的任务。

最新更新