gpt4 book ai didi

javascript - NodeJS : Don't wait for function return

转载 作者:行者123 更新时间:2023-12-03 00:51:10 25 4
gpt4 key购买 nike

我目前正在从 NodeJS 开始,我想使用不同的参数多次运行相同的函数,但我不确定如何运行。根据我目前的经验,NodeJS/JavaScript 一般不会等待函数返回,但就我而言,它确实会等待,这让我很困惑。

我当前的代码如下所示:

XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
start=function(values){
max=5
started=0
finished=0
maxReachedBefore=false
finishedStarting=false
result=[]

interval = setInterval(function(){
if(!finishedStarting){
if((started-finished)>= max) {
if(!maxReachedBefore){
console.log("Max Reached!")
maxReachedBefore=true
}
return;
}
maxReachedBefore=false
getValue(values[started])
console.log("Started getValue")
started++
} else {
if (started<=finished){
clearInterval(interval)
console.log("Finished!")
}
}

},10)
}

getValue=function(value){
var request=new XMLHttpRequest()
request.open("get","MY_WEBSITE_HERE.COM/"+value, false)
request.send()
result=result.concat(request.responseText)
console.log("Finished getValue")
finished++
}

start(["a","medium","sized","list","of","values","that","i","want","to","get","the","corresponding","values","to"])

现在我希望在未达到最大值时继续以不同的值启动 getValue -> getValue 运行次数少于 6 次,但事实并非如此。 getValue 是逐一开始的,只有在上一个完成后才开始下一个。

有人可以解释为什么会发生这种情况/帮我改变它吗?

请怜悯,我对 NodeJS 还比较陌生

最佳答案

您正在向服务器发送同步请求。因此该函数将等待服务器的响应。

request.open("get","MY_WEBSITE_HERE.COM/"+value, false)

最后一个参数boolean指定调用是同步还是异步。

request.open("get","MY_WEBSITE_HERE.COM/"+value, true)

这将发送异步调用,并在回调函数中添加完成获取值的控制台语句。

var finished = 0;
var result=[];
start=function(values){
max=5
started=0
maxReachedBefore=false
finishedStarting=false

interval = setInterval(function(){
if(!finishedStarting){
if((started-finished)>= max) {
if(!maxReachedBefore){
console.log("Max Reached!")
maxReachedBefore=true;
finishedStarting = true;
}
return;
}
maxReachedBefore=false;
console.log("Started getValue " + values[started]);

getValue(values[started]);
started++;

} else {
if (started<=finished){
clearInterval(interval)
console.log("Finished!")
}
}

},10);
}

getValue=function(value){
var request=new XMLHttpRequest()
request.open("get","MY_WEBSITE_HERE.COM/"+value, true);

request.onreadystatechange = function () {
if(request.readyState === 4 && request.status === 200) {
result=result.concat(request.responseText);
console.log("Finished getValue " + value)
finished++;
}
};
request.send();
console.log("request sent");
}

关于javascript - NodeJS : Don't wait for function return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53033128/

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