javascript - 通过 Promise 发送下载进度

标签 javascript node.js reactjs

如果我使用helperFile,我只能通过返回 Promise 将下载完成发送回组件。但是如何将进度变量发送回组件以便稍后使用它来实现下载进度条。

如果我将所有代码放入组件中,我也可以做到这一点,但这太糟糕了。

帮助文件

const request = require('request');

class helperFile{
    static downloadFile(file_url, targetPath, callback) {
        return new Promise(function (resolve, reject) {
            let received_bytes = 0;
            let total_bytes = 0;

            let req = request({
                method: 'GET',
                uri: file_url
            });

            let out = fs.createWriteStream(targetPath);
            req.pipe(out);

            req.on('response', function (data) {
                total_bytes = parseInt(data.headers['content-length']);
            });

            req.on('data', function (chunk) {
                received_bytes += chunk.length;
                let progress = (received_bytes * 100) / total_bytes;

                return progress
            });

            req.on('end', function () {
                resolve(true)
                console.log("File succesfully downloaded");
            });
        })
    }
}

react 组件

import helperFile from '../actions/download'

   handleDownloadFile() {
       helperFile.downloadFile('https:...', 'path' )
       .then((response) => console.log(response))
   }

The expected output should be 1,2,3,...100, and when finished true.

最佳答案

您可以使用回调来更新 React 组件的状态。

req.on('data', function (chunk) {
    received_bytes += chunk.length;

    const progress = (received_bytes * 100) / total_bytes;

    callback(progress);
});

在你的 React 组件中

handleDownloadFile() {
   helperFile.downloadFile('https:...', 'path', this.updateProgress)
   .then((response) => console.log(response))
}

updateProgress(progress) {
    this.setState({progress});
}

关于javascript - 通过 Promise 发送下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44717487/

相关文章:

javascript - while 循环在 JavaScript 中在新行上打印元音和其他元素

javascript - 阻止 body 集中注意力

node.js - Node index.js 命令在 Windows powershell 中被忽略

javascript - 如何判断函数有无参数

javascript - webpack - 找不到 manifest.json

文本区域文本的 Javascript 语法检查器?

javascript - 如何在 Angular 模板中包含外部javascript?

node.js - nightwatch.js 中 page_objects 中的多级部分

javascript - Nodejs中如何使用foreach获取数组的和?

HTML 输入 autoFocus 属性未使用 React.renderToStaticMarkup 呈现