Losing execution context after using await command


#1

I’m using zone.js inside my AdonisJs project to create execution context. I have a piece of middleware that creates a zone as follows:

async handle ({ request, response }, next) {
    let token = jwtDecode( request.header('Authorization') )

    // Create a zone so we have execution context throughout the flow
    await Zone.current.fork({

        name: Math.random(),
        properties: {
            username: token.username,
            user_id: token.sub
        }
    }).run( async () => {

        // call next to advance the request
        await next()
    })
}

Inside my controller I can access my zone properties with

let username = Zone.current.get('username')

However, the moment I use the await command I lose access to the zone properties, all are undefined. For example:

WORKS

let username = Zone.current.get('username') // ALL OK
let order = await Order.find(params.id);

NOT WORK

let order = await Order.find(params.id);
let username = Zone.current.get('username') // UNDEFINED

Can anybody please advise?


#2

Put your code inside try/catch and see if it works.


#3

Hi @Melchyore, unfortunately no errors are being thrown. The properties are merely undefined.


#4

I believe has Zone.js or anything built around async_hooks may get issues with async/await and that’s coz of Nodejs implementation.

Also, all the implementations that I have seen so far for global context are leaky and reason is simple that you are fighting against the nature of Javascript and Nodejs event loop.

I have plans of making parts of Adonis like Models more flexible, so that you can share http context with them.


#5

Thanks @virk appreciated. I’m a relative JS/Node novice with a lot studying in front of me. I have an immediate requirement to create an application audit trail and wanted to use the afterSave hook to record changes including who made those changes.