在我的 Session
类中,我正在创建我的 Question
类的对象。我在那里将图像下载到本地路径。现在的问题是,我的 LaTeXDoc 类要求在调用时已保存所有图像,但文件是异步下载的,这当然会导致文件在需要时不存在。
我的类(class)的电话
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/