use promises

This commit is contained in:
Thomas Ruoff
2017-02-24 21:17:10 +01:00
parent 722accbe5d
commit f51daddc65
3 changed files with 48 additions and 58 deletions

View File

@@ -5,48 +5,47 @@ const uuid = require('uuid');
const {getDirPath, getDocPath} = require('./utils');
function copyToTemp(id, texDocument, callback) {
const dirPath = getDirPath(id);
function copyToTemp(id, texDocument) {
return new Promise((resolve, reject) => {
const dirPath = getDirPath(id);
fs.mkdir(dirPath, (err) => {
if (err) {
callback(err);
return;
}
const docPath = getDocPath(id);
fs.writeFile(docPath, texDocument, (err) => {
fs.mkdir(dirPath, (err) => {
if (err) {
callback(err);
reject(err);
return;
}
callback(null);
const docPath = getDocPath(id);
fs.writeFile(docPath, texDocument, (err) => {
if (err) {
reject(err);
}
resolve(id);
});
});
});
}
function generateDoc(id, callback) {
const pdflatex = spawn('pdflatex', [getDocPath(id), '-interaction', 'nonstopmode'], {cwd: getDirPath(id)});
pdflatex.stderr.on('data', (data) => {
console.error('onData', data);
});
function generateDoc(id) {
return new Promise((resolve, reject) => {
const pdflatex = spawn('pdflatex', ['-interaction', 'nonstopmode', getDocPath(id)], {cwd: getDirPath(id)});
pdflatex.stderr.on('data', (data) => {
console.error('onData', data);
});
pdflatex.on('close', (code) => {
if (code > 0) {
callback(`pdflatex returned with code ${code}`);
return;
}
console.log(`PDF ${id} generated`);
callback(null, id);
pdflatex.on('close', (code) => {
if (code > 0) {
reject(`pdflatex returned with code ${code}`);
return;
}
console.log(`PDF ${id} generated`);
resolve(id);
});
});
}
module.exports = (texDocument, callback) => {
module.exports = function(texDocument, callback) {
const id = uuid.v1();
copyToTemp(id, texDocument, (err) => {
if (err) {
callback(err);
return;
}
generateDoc(id, callback);
});
return copyToTemp(id, texDocument)
.then(generateDoc);
};