gpt4 book ai didi

javascript - 在 javascript 中返回迭代器内的函数值而不退出

转载 作者:行者123 更新时间:2023-12-01 03:53:53 24 4
gpt4 key购买 nike

我不确定我的标题是否符合我的问题,但它就是这样。

我有一个迭代器每 1 秒运行一次,函数如下:

function getValue(val) {
return val;
}

function test() {
let x = 20;
getValue(x)

setTimeout(()=>{
test()
}, 1000)
}

export default test;

当函数 getValue() 被调用时,迭代器会停止,因为该函数内部有一个 return。如何在不退出停止迭代的情况下返回值?有办法吗?非常感谢。

<小时/>

index.js(reactjs)

import test from './test.js';

componentDidMount() {
test()
}
<小时/>

测试.js

function getValue(val) {
return val;
}

function test() {
let x = 20;
getValue(x)

setTimeout(()=>{
test()
}, 1000)
}

export default test;

我的目标是将值 20 传递/返回到我的 index.js

最佳答案

My Aim here is to pass/return the value 20 to my index.js

为此,您不需要 getValue 函数。就这么写

// test.js
export default function test() {
let x = 20;
setTimeout(test, 1000)
return x; // <===
}

// index.js
import test from './test.js';
console.log("test() returned", test());

请注意,在超时期间您现在也将获得该返回值,并且如果您关心的话可以使用它

// test.js
export default function test() {
let x = 20;
setTimeout(() => {
let res = test();
console.log("test() in timeout returned", res);
}, 1000)
return x;
}
<小时/>

any other options to this like it can pass value to the client every 1sec?

为此,您需要使用回调作为参数传递给 test,并且可以在您需要的任何时间和地点调用该回调来传递 x 的值- 并根据需要经常进行:

// test.js
export default function test(callback) {
// ^^^^^^^^
let x = 20;
callback(x); // <===
setTimeout(() => {
test(callback);
}, 1000);
}

// index.js
import test from './test.js';
function gotValue(val) {
console.log("received ", val);
}
test(gotValue);
// ^^^^^^^^

关于javascript - 在 javascript 中返回迭代器内的函数值而不退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42941594/

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