无法在此节点中添加超时 http get 请求

Unable to add a timeout in this node http get request

我有这段代码,其中函数 download 应每 5 秒调用一次,但它似乎不起作用,因为所有图像都是同时下载的。

const download = function (uri, filename, callback) {
  request.head(uri, function (err, res, body) {
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback); 
   });
};

for (let i = 0; i < 100; i++) {
  setTimeout(function () {
    download(
      'https://www.thispersondoesnotexist.com/image', 
      `images/image${i}.jpg`,
      function () {
        console.log('done');
      });
    },
    5000
  )
}

您的 setTimeout 函数是用 5000 硬编码的。这意味着您的循环是 运行 从 0 到 99 并设置 100 个超时,每个超时的等待时间为 5000。由于循环执行得非常快,因此执行的超时也非常接近。

你需要这样的东西:

 setTimeout(function() {
   ...
   },
   5000 * i
 )

这会将超时从 0 * 5000 分散到 99 * 5000 毫秒。

同步代码的执行方式是,您的所有代码都必须完成 运行ning,然后才能更新任何内容或 "rendered" 到屏幕。因此 for 循环将 运行 直到完成,然后屏幕将更新,但它当然只会呈现已执行代码的最终视图。

要在 for 循环的每次迭代中解决此问题,您应该在当前同步 for 循环代码之外触发一个异步函数,该函数将在以后更新。

例如:

    const download = function () {
        return "ready player "
    };

 for (let i = 1; i <= 10; i++) {//the code will only iterate 10 times
    setTimeout(function () {
         console.log(download()+i);
     }, 500 * i);  //reduced the timer here to 500
 }

我会用 setInterval 来重复你的方法:

const download = function (uri, filename, callback) {
  request.head(uri, function (err, res, body) {
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback); 
   });
};

setInterval(() => {
    for (let i = 0; i < 100; i++) {
        download(
          'https://www.thispersondoesnotexist.com/image', 
          `images/image${i}.jpg`,
          function () {
            console.log('done');
        });
    }
}, 5000);

我遇到了同样的问题,我用 .then() 解决了它。

const download = require("image-downloader");

function downloadIMG(opts) {
  const { filename, image } = download
    .image(opts)
    .then(({ filename }) => {
      console.log("Saved to", filename); // saved to /path/to/dest/photo
    })
    .catch((err) => console.error(err));
}