这是一个.js
const a = require("./b");
setInterval(function(){console.log(a)},1000);
这是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;
我想要的输出是这样的:
2
1
3
2
4
3
5
4
.
.
.
但是我得到的是这样的:
2
1
3
1
4
1
5
1
.
.
.
当我每秒调用a时,当a仍在另一个函数的处理过程中时,我想获得a的更新值哈哈哈 。是否有可能获取更新的值,该值不是从函数返回,而是在过程中返回?我尝试用谷歌搜索,但我不知道该使用哪个关键字。我现在感觉自己很新手。
最佳答案
您只分配一次数字,然后 a.js
将始终保持相同,并且 b.js
只导出一次变量(当他说 1)
这就是灵魂
// 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()
我在 a.js
中添加了 - 1
,因为即使您在更改之前获取了变量,也不会出现 > 2 的差异,这意味着它永远都是这样
a.js -> 2
b.js -> 2
a.js -> 3
b.js -> 3
但不包括-1
关于javascript - 如何在函数中处理时获取更新的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66516857/