简体   繁体   English

节点-等待周期内的请求响应

[英]Node - Wait request response within cycle For

Really, I've tried all ways, but I fail to find the solution. 确实,我已经尝试了所有方法,但是找不到解决方案。

As no English, and I'm using the google translator, I will explain the same thing several times in a row. 由于没有英语,所以我正在使用Google翻译,我将连续多次解释同一件事。

1º Try the For loop will wait until everything is finished within 1º尝试For循环将等待,直到一切都完成为止

2º I try to know that city is doing OK on an external web request. 2º我尝试知道某个城市在外部Web请求上运行正常。 And like many cities, I need to break the cycle once I check the first city ok. 和许多城市一​​样,一旦我检查了第一个城市就可以了,我需要打破循环。

3º I need to go a json and execute an action while running and wait till it finishes to follow. 3º我需要运行一个json并在运行时执行一个动作,然后等待其完成。 Then get out of the cycle at any time. 然后随时退出循环。


I've been testing with several codes, but present here for better understanding. 我一直在用几个代码进行测试,但是为了更好的理解在这里出现。

---------------------------------------------------------------------

var city = 
[
    {'city':'madrid'},
    {'city':'barcelona'},
    {'city':'valencia'},
    {'city':'malaga'}
];

var vBreak = 0;

for (i in city){

    request('example.there-city.com/' + city[i].city ,function (error, response, read) {
        if (read == 'OK') { vBreak = 1}
    });

if (vBreak == 1){ break;}
}

var city = 
[
    {'city':'madrid'},
    {'city':'barcelona'},
    {'city':'valencia'},
    {'city':'malaga'}
];

var vBreak = 0;

for (i in city){

    (function(i) {
        request('example.there-city.com/' + city[i].ciudad ,function (error, response, read) {
            if (read == 'OK') { vBreak = 1}
        });
    })(i);

if (vBreak == 1){ break;}
}

Thank you 谢谢

Use async.eachSeries (as jgillich said) to perform each request in order like this: 使用async.eachSeries(如jgillich所述)按以下顺序执行每个请求:

async.eachSeries(city, function (item, cb) {
  if (vbreak !== 1) {
    request('example.there-city.com/' + item.city ,function (error, response, read) {
        if (read == 'OK') { vBreak = 1}
        cb();
    });
  } else {
    cb() // Skip
  }
}, function () { // we're finished
})

You'll need to add error handling probably. 您可能需要添加错误处理。

Try to use a recursive function. 尝试使用递归函数。 Just increment the counter, after the response came ... 响应后,只需增加计数器即可...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM