【问题标题】:NodeJS - Get an array from an async for loopNodeJS - 从异步 for 循环中获取数组
【发布时间】: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') }
})

【问题讨论】:

标签: javascript node.js for-loop asynchronous


【解决方案1】:

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

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 已经包含在 Promise https://github.com/request/request-promise-native

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

【讨论】:

  • 我也只是使用 request-promise 模块,而不是将您自己的 promise 包装在 request 周围。它还具有自动为您解析 JSON 并自动为您检查状态代码的选项。
  • 是的,我把它放在我的评论里了。
  • 为什么不在您的答案代码中显示它? IMO,这将是一个更好的答案。
  • JS 新手是开始使用 request-promise 而不是 request 的正确时机。对常规回调的承诺。而且,最好教别人使用承诺的现有模块,而不是重复承诺已经完成并广泛使用的东西。
  • Promise.all() 上缺少.catch() 处理程序,或者需要返回Promise.all() 承诺。对来自 for 循环的承诺没有错误处理。
猜你喜欢
  • 2019-02-15
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
  • 2021-02-21
相关资源
最近更新 更多