0

This is my code:

let observe = (obj: any, fn: any) => new Proxy(obj, {
    set: (obj, key, val) => {
      fn(obj)
      return obj[key] = val;
    }
});

router.use('/', async (req, res) => {
  const id = req.query.id

  arrs = observe([], (arr: any) => {
    console.log("current", id)
  });

  setTimeout(() => {
    arrs.push(id);
  }, 5000);
}

Everything is ok, but console.log("current", id) does not work correct.

1- I open this url

http://localhost:9000/?id=a

2- after one second, I open this url:

http://localhost:9000/?id=b

3- after five seconds, id push to arrs and console.log("current", id) printed:

current b
current b

why?!

The correct result most be:

current a
current b
ali
  • 55
  • 1
  • 6
  • arrs is being added to the global object, maybe it's being overwritten? – eroironico Dec 06 '22 at 15:22
  • `arrs` is a global, so by the time `setTimeout` calls the callback, both calls to `arrs.push` are accessing the second array. – Quentin Dec 06 '22 at 15:23
  • This is [one type of problem that ESLint can spot for you](https://eslint.org/docs/latest/rules/no-implicit-globals#global-variable-leaks). – Quentin Dec 06 '22 at 15:24
  • @Quentin So, How can I fix it? – ali Dec 06 '22 at 15:25
  • Declare a local variable as described in the accepted answer of the duplicate question. – Quentin Dec 06 '22 at 15:25
  • @Quentin I can't. because I use `arrs` in separate place. – ali Dec 06 '22 at 15:26
  • @ali — Currently you are using a global which is shared between all requests, that isn't working for you so you can't store it there. You haven't explained where you do need to use it and how that relates to the different requests you might get from the same or different users, so we can't really suggest what the right place might be. – Quentin Dec 06 '22 at 15:28
  • @Quentin I use rabbitmq for connect another server. so I write this code for consume response from another server and after consume, I updated `arrs`. after `arrs` updated, I send `res` to api gateway – ali Dec 06 '22 at 16:12
  • I can't see your RabbitMQ client code, and I'm not all that familiar with its API, but I *assume* that when you send a message to RabbitMQ you get a response that is already associated with that message. Pass `res` to whatever function is dealing with that so it is available to the response handling code. Better yet, wrap it in a promise and `await` it inside your endpoint handler. – Quentin Dec 06 '22 at 16:17
  • @Quentin I can't use await for rabbitmq. because for one channel I can't handle it. – ali Dec 06 '22 at 16:23

0 Answers0