Skip to content

Conversation

wujjpp
Copy link

@wujjpp wujjpp commented Mar 13, 2021

[AsyncLocalStorage] getStore() return undefine after call redis command

The async_hooks module provides an API to track asynchronous resources. but in current version of node-redis, it cause missing context after executing redis command

Tesing code

/* eslint-disable no-console */
const redis = require('redis')
const { AsyncLocalStorage } = require('async_hooks')
const express = require('express')

const client = redis.createClient({
  host: '127.0.0.1',
  port: 6379,
  password: 'xxxxx',
  db: 1
})

const asyncLocalStorage = new AsyncLocalStorage()

const app = express()

app.use((req, res, next) => {
  // prepare store, assume "new Date().getTime()" is 1615527591298
  asyncLocalStorage.enterWith({ now: new Date().getTime() })
  next()
})

app.use((req, res, next) => {
  // get store from asyncLocalStorage
  console.log(asyncLocalStorage.getStore()) // output: {now: 1615527591298}
  next()
})

app.use((req, res, next) => {
  client.get('foo', (err, data) => {
    if (err) {
      next(err)
    }
   // get store from asyncLocalStorage
    console.log(asyncLocalStorage.getStore())  // expect output "{ now: 1615527591298 }", but undefined.
    next()
  })
})

app.use((req, res, next) => {
  // get store from asyncLocalStorage
  console.log(asyncLocalStorage.getStore()) // expect output "{ now: 1615527591298 }", but undefined.
  next()
})

app.get('*', (req, res) => {
  res.send('nothing')
})

app.listen(8080, err => {
  if (err) {
    console.error(err)
  } else {
    console.log('Server listening on port 8080')
  }
})

Tesing result

curl http://127.0.0.1:8080

Expect output:

{ now: 1615527591298 }
{ now: 1615527591298 }
{ now: 1615527591298 }

Actual output:

{ now: 1615527591298 }
undefined
undefined

This patch for fixing the issue

@wujjpp wujjpp changed the title [AsyncLocalStorage] getStore() return undefine after call redis command [AsyncLocalStorage] For fixing asyncLocalStorage.getStore() return undefined after call redis command May 11, 2021
@toufali
Copy link

toufali commented Feb 28, 2023

I came across this issue as well and want to +1 in hope of this fix.

@toufali
Copy link

toufali commented Feb 28, 2023

Update – this issue is resolved for me with the latest version 4.6.5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants