node-redis icon indicating copy to clipboard operation
node-redis copied to clipboard

[AsyncLocalStorage] For fixing asyncLocalStorage.getStore() return undefined after call redis command

Open wujjpp opened this issue 4 years ago • 2 comments

[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 avatar Mar 13 '21 03:03 wujjpp