【发布时间】:2018-08-09 00:22:40
【问题描述】:
我对 nodejs 编码还很陌生,遇到了一个问题,我无法将我可以登录控制台的项目放入一个数组中,以便从每个发出 url 请求的循环中进行处理。
这里的代码首先从请求中获取键列表,然后我使用 for each 循环中的另一个请求将其转换为名称。
我需要将名称列表记录在一个数组中,上面写着“这里需要一个数组”,这是我当前的代码:
request('https://api2.ripaex.io/api/delegates/getNextForgers', function (error, response, body) {
if (!error && response.statusCode == 200) {
var jsonContent = JSON.parse(body);
var delegates = jsonContent.delegates;
for (i = 0; i < delegates.length; ++i) {
request(String('https://api2.ripaex.io/api/delegates/get?publicKey=' + delegates[i]), function (error, response, body) {
if (!error && response.statusCode == 200) {
var jsonContent2 = JSON.parse(body);
console.log(jsonContent2.delegate.username);
}
})
}
console.log('need an array here');
} else { console.log('Error: Could not retrieve the data') }
})
【问题讨论】:
-
请求是异步函数。你不能那样做。你应该研究一下承诺。 developers.google.com/web/fundamentals/primers/promisesgithub.com/request/request-promise-native
标签: javascript node.js for-loop asynchronous