首页 > 解决方案 > 异步函数挂起/恢复时是否可以透明地触发回调?

问题描述

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

所需功能的伪代码示例:

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'

标签: javascriptasynchronousasync-awaitcallbackmiddleware

解决方案


您可能正在寻找node.js 中的异步钩子,它可以跟踪 promises

语言中没有标准的内置结构。如果您想基于这样的东西构建自己的框架,请改用生成器函数并提供一个运行器来逐步执行生成的任务。


推荐阅读