javascript - Node - 在 For 周期内等待请求响应

标签 javascript json node.js for-loop asynchronous

真的,我已经尝试了所有方法,但没有找到解决方案。

由于我不会英语,而且我正在使用谷歌翻译,所以我会连续解释几次同样的事情。

1º 尝试 For 循环将等待一切​​完成

2º 我尝试了解该城市在外部网络请求方面表现良好。和许多城市一​​样,一旦检查第一个城市正常,我就需要打破循环。

3º 我需要读取 json 并在运行时执行一个操作,然后等待它完成。然后随时跳出循环。

<小时/>

我已经使用多个代码进行了测试,但在这里展示是为了更好地理解。

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

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;}
}

谢谢

最佳答案

使用 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
})

您可能需要添加错误处理。

关于javascript - Node - 在 For 周期内等待请求响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26553154/

相关文章:

python - 如何在 Python 2.7 中从文件中读取字典?

javascript - Node 中是否需要使用 eval 来运行另一个文件中的代码

javascript - 用 object.create 定义的原型(prototype)的构造函数属性从哪里来?

php - 如果存在值,如何禁用文本字段或输入?

javascript - ANTLR4 JavaScript 解析器 : how to catch an error in parsing

javascript - 在使用 @loadable/component 渲染之前等待 Promise

java - 使用 Jackson 检查 JSON 在 JAVA 中是否有效

java - Camel Rest DSL 响应编码

node.js - 如何从 lambda 访问 Cognito 联合身份中的身份数据集

node.js - 如何使用 "Non Atomic"批处理/管道在 Scylla 中运行多个查询