我目前从NodeJS开始,我想使用不同的参数一次多次运行Same函数,但是我不确定如何运行。 根据我的当前经验,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来说还比较陌生]
答案 0 :(得分:1)
您正在向服务器发送同步请求。因此该功能将等待服务器的响应。
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");
}
这将发送异步调用,并在回调函数中添加完成获取值的控制台语句。
!define MUI_DEFAULT_MUI_WELCOMEFINISHPAGE_BITMAP "E:\Code\PCPE\NULLSOFT\src\Bitmaps\dlgbmp-for-china.bmp"