如果我使用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/