微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

以相同的顺序从链接列表中下载图像

如何解决以相同的顺序从链接列表中下载图像

我需要像这样从一系列链接中下载图像https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png

还有我写的代码。我用了 https://www.npmjs.com/package/image-downloader

const download = require('image-downloader');
const links = require('./links.json');

var options = {
  url: "",dest: links.dest,};

  links.url.forEach((link) => {
    options.url = link
   download
    .image(options)
    .then((result) => {
      console.log("Image downloaded",result);
    })
    .catch((error) => console.log("downloaded error",error));
  });

和 .json 文件

{
"url":[
"https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png","https://api.time.com/wp-content/uploads/2019/08/better-smartphone-photos.jpg","https://iso.500px.com/wp-content/uploads/2016/03/stock-photo-142984111.jpg",]
"dest":"D:/"
}

但是因为它是异步工​​作的,所以所有下载的图像都是无序的,不像链接列表中的那样(不能按日期排序)。如何修改代码以使其按顺序下载图像?

解决方法

看看这个:Creating a promise chain in a for loop

您的图像下载器使用 JS Promises 来下载图像,因此您要做的不是调用 3 个 Promise,而是您希望使用 for 循环链接这些 Promise。为此,请按照 Stack Overflow 答案中的示例操作,将 .forEach 循环替换为常规 for 循环。

,

使用 async/await 同步循环遍历您的列表,并使用以下函数来完成

编辑:在使用 javascript 时使用 async/await 或使用 Promise.all 以不阻塞 javascript 事件循环。

const asyncForEach = async (array,callback) => {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index],index,array)
  }
}

var options = {
  url: "",dest: links.dest,}

// use it like so:
await asyncForEach(links.url,async link => {
  try {
    options.url = link
    const result = await download.image(options)
    console.log("Image downloaded",result)
  } catch (err) {
    console.error(err)
  }
})
,

使用 Promise.all - 当一个 promises 数组中的每个 promise 都解析时,它会解析,并以原始顺序返回所有结果的数组!我建议您避免在此处使用 for 循环,因为当并行下载图像时可以更有效地下载图像,这将依次下载图像!

let download = require('image-downloader');
let links = require('./links.json');

let options = { url: '',dest: links.dest };

let allLinksDownloadedPromise = Promise.all(links.url.map(link => {
  return download.image({ ...options,link });
}));

allLinksDownloadedPromise.then(arrayOfDownloads => console.log('Downloaded:',arrayOfDownloads));
,

使用 for-loopasync/await 语法使其变得简单。

const download = require('image-downloader');
const links = require('./links.json');

(async () => { // `await` can only be used inside an async function.
  try {
    for (const url of links.url) {
      // wait until downloading process finish then continue to solve next url
      const result = await download.image({ url,dest: links.dest });
      console.log("Image downloaded",result);
    }
    console.log("Done!");
  } catch(error) {
    console.log("downloaded error",error)
  }
})();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。