gpt4 book ai didi

javascript - 如何在函数中处理时获取更新的值

转载 作者:行者123 更新时间:2023-12-04 08:00:06 29 4
gpt4 key购买 nike

这是 a.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.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()
我添加了一个 - 1a.js因为,即使你在变量改变之前得到了变量,你也永远不会有 > 2 的差异,这意味着它永远是这样的
a.js -> 2
b.js -> 2
a.js -> 3
b.js -> 3
但不是 -1

关于javascript - 如何在函数中处理时获取更新的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66516857/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com