在我的Session
类中,我正在创建我的Question
类的对象。在这里,我将图像下载到本地路径。现在的问题是我的LaTeXDoc
类要求在调用时已经保存了所有图像,但是文件是异步下载的,这有可能导致文件在需要时不存在。
我班的电话
router.post('/upload', upload.single('session'),function(req, res) {
var session_file = JSON.parse(fse.readFileSync(req.file.path, 'utf-8'));
// Session creates the Question objects
var session = new Session(session_file);
var tex = new LaTeXDoc(session); // files should already downloaded here
...
res.sendFile(path.resolve("./tmp/"+tex.pdf_name));
});
题
const randomstring = require("randomstring");
var http = require('https');
var fs = require('fs');
class Question{
constructor(type, variant, subject, text, possibleAnswers, hint, solution, imageURL){
...
this.imageURL = imageURL
this.imageName = randomstring.generate()+".png";
var options = {
url: this.imageURL,
dest: './tmp/'+this.imageName
}
if (this.imageURL != null){
var file = fs.createWriteStream(options.dest);
var request = http.get(options.url, function(response) {
response.pipe(file);
console.log(file.path) // => /path/to/dest/image.jpg
});
}
}
}
现在,当我创建
LaTeXDoc
类时,如何确保文件存在? 最佳答案
如果您需要能够知道它们何时完成了异步操作,则需要在API中使用Promise或回调。这确实意味着您需要将异步操作移出对象构造函数,并移至某种init方法中。
前
function init(cb) {
http.get(options.url, function(response) {
response.pipe(file);
console.log(file.path) // => /path/to/dest/image.jpg
return cb();
});
}
关于javascript - 在创建对象之前等待文件下载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52929468/