简体   繁体   English

从数组中的链接下载文件

[英]Download files from links in array

I'm trying to download files from links in an array with a length of several thousand positions. 我正在尝试从具有数千个位置的数组中的链接下载文件。 The problem is that when I iterate over the array I hit a wall when trying to synchronize the file fetch and write ( Maximum call stack size exceeded). 问题是,当我遍历数组时,尝试同步文件获取和写入时,我碰到了墙(超过了最大调用堆栈大小)。 I've tried to make a recursive function and played with promises but I still haven't managed to find a solution. 我试图做一个递归函数,并与promises一起玩,但是我仍然没有找到解决方案。 Help please! 请帮助!

My code so far: 到目前为止,我的代码:

 function download(url, dest, cb) { return new Promise(function (resolve, reject) { let request = https.get(url, function (response) { let file = fs.createWriteStream(dest); response.pipe(file); file.on('finish', function () { console.log('File downloaded') resolve(file.close(cb)); }); }).on('error', function (err) { reject(err) }); }) }; function recursiveDownload(links, i) { if (i < links.length) { download(links[i], './data/' + i + '.csv') .then(recursiveDownload(links, ++i)) } else { console.log('ended recursion') } } recursiveDownload(links, 0) 

You can use a for loop to serialize all your promises and synchronize them. 您可以使用for循环序列化所有诺言并进行同步。 Try the following: 请尝试以下操作:

var promise = Promise.resolve();
for(let i = 0; i < links.length; i++){
  promise = promise.then(()=> download(links[i], './data/' + i + '.csv'));
}

Or you can even chain your promises using Array.reduce() : 或者甚至可以使用Array.reduce()链接您的诺言:

var promise = links.reduce((p, link, index) => p.then(()=>download(link, './data/' + index + '.csv')),Promise.resolve());

Because you call recursiveDownload immeadiately withou waiting for the download to succeed. 因为您立即调用recursiveDownload下载,所以没有等待下载成功。 You actually want to call it when .then calls back: 您实际上想在.then回叫时调用它:

 download(links[i], './data/' + i + '.csv')
        .then(() => recursiveDownload(links, ++i))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM