Hi Everone I am using async_hook for request context console.log("xxx",hook.getRequestContext()) // undefined because of i am using promise before
var hook = require('../../services/hooks.service');
const test11 = async (req,res)=>{
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
await myPromise
console.log("xxx",hook.getRequestContext()) // undefined because of i am using promise before
}
hook.service.js
const asyncHooks = require('async_hooks');
const { v4 } = require('uuid');
const store = new Map();
const asyncHook = asyncHooks.createHook({
init: (asyncId, _, triggerAsyncId) => {
if (store.has(triggerAsyncId)) {
store.set(asyncId, store.get(triggerAsyncId))
}
},
destroy: (asyncId) => {
if (store.has(asyncId)) {
store.delete(asyncId);
}
}
});
asyncHook.enable();
const createRequestContext = (data, requestId = v4()) => {
const requestInfo = { requestId, data };
console.log(asyncHooks.executionAsyncId())
store.set(asyncHooks.executionAsyncId(), requestInfo);
return requestInfo;
};
const getRequestContext = () => {
console.log(asyncHooks.executionAsyncId())
return store.get(asyncHooks.executionAsyncId());
};
module.exports = { createRequestContext, getRequestContext };
app.js
const hook = require('./src/services/hooks.service');
app.use((request, response, next) => {
const data = { headers: request.headers };
hook.createRequestContext(data);
next();
});
What should I do? I want to get context after the promise. but I am getting undefined why i am getting undefined because asyncHooks.executionAsyncId() getting new id after promise