【问题标题】:Looping a request that returns results in order they were put in循环返回结果的请求,按放入的顺序
【发布时间】:2016-09-08 09:17:31
【问题描述】:

此代码与我的代码结构相同:

for (var i in UserNameArray)
        {
 var Urls = "https://some online api"+UserNameArray[i]+"api key";
 //the url changes by plugging in the next array value every iteration.
            request({
                url: Urls,
                json: true
            }, function (error, response, body) {

                if (!error && response.statusCode === 200) {
                    console.log(body); 
                }
            })
        }

它正确地从 URL 返回一个 json,但它打印出来,每个迭代的请求首先返回。如何更改我的代码,以便它按照请求的顺序打印出请求?这很重要,因为我必须使用来自 UserNameArray 的特定值遍历特定 JSON。

【问题讨论】:

  • 得到body之后除了console你到底想做什么?
  • 我知道你可以用这个库实现它caolan.github.io/async
  • 在for循环上方声明了另一个名为IdResultArray的数组,那我就说IdResultArray [i] = body[UserNameArray[i]].id。然后我将使用它更新我的数据库,并使用 express 和 EJS 将其输出到网页。
  • 其实这是我的 async.waterfall 中的一个函数,async 模块的哪一部分会帮我解决这个问题?

标签: json node.js httprequest


【解决方案1】:

试试这个。

我将遍历所有这些,并将响应存储在结果数组中(按索引)。然后,当所有这些都完成后,它会进入最终回调,我们将它们(按顺序)打印到控制台。

var async =  require('async'); 
var result = [];

async.eachOf(UserNameArray, function(name, i, cb) {

    //the url changes by plugging in the next array value every iteration.
   var Urls = "https://some online api"+UserNameArray[i]+"api key";
  request({
    url: Urls,
    json: true
  }, function (error, response, body) {

    // checking if something went wrong..    
    if (error) return cb(error);

    if (!error && response.statusCode === 200) {

        // storing the response to our result array
        result[i] = body;
        // do a callback, telling that we are done here
        cb();
    }

  })

}, function(err) {

        // all done.

        // lets print the errors if something went wrong
        if (err) console.error(err.message);

        // lets print our results
        for(var i=0; i<result.length; i++) {
        console.log(result[i]);
    }
});

【讨论】:

    【解决方案2】:

    在使用 npm 安装异步之前试试这个

    var async =  require('async'); 
    async.forEach(UserNameArray, function (i, cb) {
    
            var Urls = "https://some online api"+i+"apikey";
            request({
                url: Urls,
                json: true
            }, function (error, response, body) {
    
                if (!error && response.statusCode === 200) {
                    console.log(body); 
    
                }
               cb();
            })
    
          });
    

    【讨论】:

    • 感谢您的回复,我实现了您的回复,不幸的是,它仍然返回结果,而不是按照它们放入的顺序。我把它放在我的瀑布中的一个函数中,它也在所有函数之后运行瀑布完成了。
    猜你喜欢
    • 2016-07-11
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多