首页 > 解决方案 > 有没有办法为 NodeJs 异步执行“线程”获取某种“上下文”?

问题描述

当你有一个用 async/await 编写的 NodeJS HTTP 服务器时,有一个可用的“上下文”会非常好。例如:

httpServer.on('request', funcA);

async function funcA(req) {
    await funcB();
}

async function funcB(req) {
    await funcC();
}

async function funcC(req) {
   await someApi.call();
   // I want to access the original HTTP request here! And other notes I've gathered about
   // the request while processing it in funcA() and funcB().
}

目前我知道的唯一方法是将上下文对象作为参数传递给您调用的每个函数。这可行,但是您的代码到处都是context参数。从字面上看,您编写的每个函数都需要将其作为参数并将其传递给其他所有函数,因为某处可能需要它。这很烦人。

如果有一个getContext()可以在任何地方调用并返回当前上下文对象的函数会更好。但我不知道我怎么能做到这一点,以及如何确定当前的“请求线程”,如果你可以这样称呼它的话。

有什么办法吗?

标签: node.jspromiseasync-awaites6-promise

解决方案


推荐阅读