How to get updated value while processing in a function

Viewed 64

This is a.js

const a = require("./b");

setInterval(function(){console.log(a)},1000);

This is b.js

let a = 1;
async function hahaha(){
    while(true){
        await sleep(1000);
        a += 1;
        console.log(a)
    }
}

function sleep(ms) {
    return new Promise((r) => setTimeout(r, ms))
}
hahaha()

module.exports = a;

My desired output is this:

2
1
3
2
4
3
5
4
.
.
.

But what I get is this:

2
1
3
1
4
1
5
1
.
.
.

I want to get an updated value of a when I call it every second while a is still in the process of another function hahaha. Is it possible to get updated values, which is not returned from a function, but in the process? I tried to google it, but I don't know which keyword to use. I feel so newbie now.

2 Answers

When you pass a non-object value, its pass by value hence you are receiving the initial value 1 and it doesn't change/update

In order to get the expected result, please wrap your variable a in JSON object in b.js and export that JSON object.

b.js would look like-

const container={a:1};
async function hahaha(){
    while(true){
        await sleep(1000);
        container.a += 1;
        console.log("Logged from b.js - ",container.a)
    }
}

function sleep(ms) {
    return new Promise((r) => setTimeout(r, ms))
}
hahaha()

module.exports = container;

a.js would be then enhanced to -

const container = require("./b");

setInterval(function(){console.log("Logged from a.js - ",container.a)},1000);

Output on running a.js would be -

Logged from a.js -  1
Logged from b.js -  2
Logged from a.js -  2
Logged from b.js -  3
Logged from a.js -  3
Logged from b.js -  4
Logged from a.js -  4
Logged from b.js -  5
Logged from a.js -  5
Logged from b.js -  6
Logged from a.js -  6
Logged from b.js -  7

You're only assigning once the number, then a.js will always stay the same and same for b.js which is only exporting the variable once (when his state it 1)

This is the soultion

// a.js
  setInterval(() => {
      const a = require('./b')
      console.log('a.js', a -1)
    }, 1000)
// b.js
let a = 1

async function hahaha() {
  while (true) {
    module.exports = a

    await sleep(1000)
    a += 1
    console.log('b.js', a)

  }
}

function sleep(ms) {
  return new Promise((r) => setTimeout(r, ms))
}
hahaha()

I've added a - 1 to the a.js cause, even if you got the variable before it changed, you wont never have a > 2 difference, meaning it will always be like this

a.js -> 2
b.js -> 2
a.js -> 3
b.js -> 3

but not with the -1

Related