NodeJS - 从异步 for 循环中获取数组



我对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') }
})

我没有测试这个,但这就是我在评论中提到的。

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;
var promises = [];
for (i = 0; i < delegates.length; ++i) {
promises.push(new Promise(function(resolve, reject) {
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);
resolve(jsonContent2);
}else{
reject(error);
}
})
}
));
}
Promise.all(promises).then(function(resultsArray){
console.log('need an array here');
}).catch(function(err){
//Handle errors
});
} else {
console.log('Error: Could not retrieve the data')
}
});

但这是已经包装在承诺中的请求 api https://github.com/request/request-promise-native

下面是使用请求-承诺 API 的未经测试的示例。

var rp = require('request-promise');
rp({
method: 'GET',
uri: 'https://api2.ripaex.io/api/delegates/getNextForgers',
json: true // Automatically stringifies the body to JSON
//resolveWithFullResponse: true //If you want the full response
}).then(function(jsonContent) {
var delegates = jsonContent.delegates,
promises = [];
for (i = 0; i < delegates.length; ++i) {
promises.push(rp({
url: String('https://api2.ripaex.io/api/delegates/get?publicKey=' + delegates[i]),
json: true
}).then(function(jsonContent2) {
console.log(jsonContent2.delegate.username);
return jsonContent2;
}));
}
return Promise.all(promises).then(function(resultsArray) {
console.log('need an array here');
});

}).catch(function(err){
console.log('Error: Could not retrieve the data')
});

最新更新