NodeJS - Get an array from an async for loop

I am fairly new to nodejs coding and ran into a problem where i can't get the items i can log in console into an array for processing from a for each loop which makes a url request.

The code here first gets a list of keys from a request which i then turn into names using another request in the for each loop.

I need to log the name list in an array where it says 'need an array here', here is my current code:

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 answer

  • answered 2018-08-09 00:40 Jerinaw

    I did not test this, but this is what I was referring to in the comment.

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

    But here is the request api already wrapped in promises https://github.com/request/request-promise-native

    Here's an untested example using the request-promise 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')
    });