数组填充顺序错误

Array filled in the wrong order

本文关键字:错误 顺序 填充 数组      更新时间:2023-09-26

我有一个奇怪的问题,当我在我的数组中推我的结果,结果不是在我的数组中的正确位置(例如,结果而不是在索引号1是在索引3),当我重新运行我的模块结果在数组中随机改变位置。

var cote = function(links, callback) {
  var http = require('http');
  var bl = require('bl');
  var coteArgus = [];
  for (i = 0; i < links.length; i ++) {
    http.get('http://www.website.com/' + links[i], function(response) {
      response.pipe(bl(function(err, data) {
        if (err) {
         callback(err + " erreur");
         return;
        }
        var data = data.toString()
        newcoteArgus = data.substring(data.indexOf('<div class="tx12">') + 85, data.indexOf(';</span>') - 5);
        myresult.push(newcoteArgus);
        callback(myresult);
      }));
    });   
  }
};
exports.cote = cote;

问题在于,尽管for是同步的http.getpipe操作不是(I/O在nodejs中是异步的),因此数组的顺序取决于哪个请求和管道首先完成,这是未知的。

尽量避免在循环中进行异步操作,而是使用像async这样的库来进行流控制。

我认为这可以按照正确的顺序完成,使用async map

下面是一个带有map和using request模块的示例。

// There's no need to make requires inside the function,
// is better just one time outside the function.
var request = require("request");
var async = require("async");
var cote = function(links, callback) {
  var coteArgus = [];
  async.map(links, function(link, nextLink) {
    request("http://www.website.com/" + link, function(err, response, body) {
       if (err) {
        // if error so, send to line 28 with a error, exit from loop.
        return nextLink(err);
       }
       var newcoteArgus = body.substring(
        body.indexOf("<div class='tx12'>") + 85,
        body.indexOf(";</span>") - 5
       );
       // pass to next link, and  add newcoteArgus to the final result
       nextLink(null, newcoteArgus);
    });
  },
  function(err, results) {
    // if there's some errors, so call with error
    if(err) return callback(err);
    // there's no errors so get results as second arg
    callback(null, results);
  });
};
exports.cote = cote;

还有一件事,我不确定,真的你在做什么,你在响应中搜索html内容的部分,但有一个非常好的库,从服务器端使用JQuery选择器可能会对你有用。

下面是你应该如何调用函数
// Call function sample.
var thelinks = ["features", "how-it-works"];
cote(thelinks, function(err, data) {
  if(err) return console.log("Error: ",  err);
  console.log("data --> ", data);
});