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

时间:2018-08-09 00:22:41

标签: javascript node.js for-loop asynchronous

我对Node.js编码相当陌生,遇到了一个问题,即我无法获取可登录控制台的数组中的项,这些数组可以从发出URL请求的每个循环中进行处理。

这里的代码首先从请求中获取键列表,然后我使用for每个循环中的另一个请求将其转换为名称。

我需要将名称列表记录在一个数组中,上面写着“这里需要一个数组”,这是我当前的代码:

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

1 个答案:

答案 0 :(得分:2)

我没有对此进行测试,但这是我在评论中所指的。

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

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

这是一个使用请求承诺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')
});