Electron-dl使用promise.all可以同时进行多个下载

时间:2018-07-05 05:55:29

标签: javascript node.js electron

我正在使用Electron-dl 根据{{​​3}} 下载功能download(window,URL,Options)仅接受网址 并返回承诺

目标:

  1. 我想同时下载文件数组
  2. then ()中,我要获取给定数组的dl.getSavePath()路径
  3. catch()中,我想获取给定数组中失败项目的错误
  4. 可以保证所有工作吗?还有其他选择吗?

代码有什么问题then()会立即被调用,而不是等待所有下载完成

压缩文件:

documentation
使用npm install && npm start

Big_array_test:

  var files = [
    'https://download.filezilla-project.org/client/FileZilla_3.34.0_win64-setup_bundled.exe',
    'http://the.earth.li/~sgtatham/putty/latest/w32/putty-0.70-installer.msi',
    'http://speedtest.ftp.otenet.gr/files/test10Mb.db'
  ]

代码:

var files= [
'http://speedtest.ftp.otenet.gr/files/test100k.db', 
'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png'];
      var promises = [];
      var _browserWindow = BrowserWindow.getFocusedWindow();
      //
      for (var i = 0; i < files.length; i++) {
        promises.push(download(_browserWindow, files[i], {
          directory: os.tmpdir() // Default is User's downloads directory
        }).then(function (dl) {
          return dl.getSavePath();
        }).catch(function (err) {
          return err;
        }));            
      }
      Promise.all(promises)
        .then(function (_files) {
          console.log(_files);
        }).catch(function (err) {
          console.log( err);
        });

1 个答案:

答案 0 :(得分:4)

我认为您的代码还可以-除非注释中所说,否则您可能不应该在promises.push中捕获错误,而应该在Promise.all中进行修改。

我从您的zip中运行了该应用程序,它可以正常工作并正确下载了2个文件。

但是随后我尝试更改一些URL并放置一个不存在的URL:好,这就是问题所在。在这种情况下,download函数不会解决诺言(这是正常的),也不会拒绝诺言(它应该如此)。

尝试自己运行以下简单代码:

download(mainWindow, 'https://nothing.wrong-url.org', {
  directory: os.tmpdir() // Default is User's downloads directory
}).then(function (dl) {
  console.log(dl.getSavePath());
}).catch(console.error)

诺言只是悬而未决,不会解决也不会拒绝。您可能会在electron-dl Github上发布一个问题。

相关问题