javascript - 创建对象之前等待文件下载

标签 javascript node.js express asynchronous async-await

在我的 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/

相关文章:

json - 使用 Node 或 Express 返回 JSON 的正确方法

node.js - ERR_MODULE_NOT_FOUND

javascript - 如何仅使 li 值可点击并生成 anchor ?

javascript - 使用 Laravel 4+ 从 jQuery/ajax 保存序列化可排序数据

javascript - 为什么 html2canvas 生成模糊的 pdf 文件?

javascript - angular js不发布表格

javascript - 以编程方式删除缓存文件并为其释放分配的内存

javascript - 在 Express/Node 中使用 LIKE SQL 语句

node.js - 在express.js Controller 中await 是否会影响性能?

node.js - 将数据传递给 View 时,node ejs 引用错误数据未在 eval 处定义